I want to make a containers width shrink to the size of an image. The height is given in percent relative to the browser window.
.img
{
width: auto;
height:100%;
}
.container
{
height:100%;
width:auto;
}
Here is the fiddle:
http://jsfiddle.net/EdgKr/68/
display:table
, like in similar cases doesnt work, because as a table cell, the image is always displayed 100% percent of its original size.
http://jsfiddle.net/EdgKr/67/
To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container.
Values. Defines the height as an absolute value. Defines the height as a percentage of the containing block's height. The browser will calculate and select a height for the specified element.
percentage - Sets the width and height of the background image in percent of the parent element. The first value sets the width, and the second value sets the height. If only one value is given, the second is set to auto . For example, 100% 100% or 50% .
The max-height property sets the maximum height of an element, and the max-width property sets the maximum width of an element. To resize an image proportionally, set either the height or width to "100%", but not both. If you set both to "100%", the image will be stretched.
Since I asked that question, I made some progress, the sollution was incredibly simple: Just add float:left.
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html,
body {
height:100%;
width:100%;
}
.container {
background: green;
float: left;
height: 100%;
}
.img {
width:auto;
height:100%;
}
The container shrinks as expected, even if the image has a percentage height. http://jsfiddle.net/EdgKr/74/
But it's very easy to break, For example, if you add padding. http://jsfiddle.net/EdgKr/72/
I think I get a better solution of this problem. Please check my code:
<!DOCTYPE HTML>
<html>
<head>
<title>Knowledge is Power</title>
<style type="text/css">
* {
-webkit-box-sizing: border-box; /* Android = 2.3, iOS = 4 */
-moz-box-sizing: border-box; /* Firefox 1+ */
box-sizing: border-box; /* Chrome, IE 8+, Opera, Safari 5.1 */
}
html, body
{
height:100%;
width:100%;
padding:10px;
}
.container {
padding:0;
background:green;
}
.img {
display: inline;
height:100%;
}
</style>
</head>
<body>
<span class="container">
<img class="img" src="a.jpg"/>
</span>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With