html - Dynamic element height to match background cover dimensions -
i'm using following css set cover background image on element:
.bg { background: url(images/kitteh1.jpg) no-repeat; background-size: cover; background-position: center; height: 200px; }
what right, css-only, way of having element size match of background image, such image first takes 100% width, , takes height necessary fit original aspect ratio?
here's playground: http://jsfiddle.net/e5ek812c/
as far know, css never aware of image size. can do, however, set padding-top
or padding-bottom
image's ratio (height is56.25%
of width here).
explanation
padding-top
, when set percentage, uses element's width reference (100%
). unlike height
.
.a { background-color: #ddd; } .bg { background: url(https://prinzhorn.github.io/skrollr/examples/images/kitteh1.jpg) no-repeat; background-size: cover; background-position: center; padding-top: 56.25%; } .c { background-color: #aaa; }
<div class="a">hello</div> <div class="bg"></div> <div class="c">bye</div>
Comments
Post a Comment