Sunday, 15 February 2015

html - Dynamic element height to match background cover dimensions -


I am using the following CSS to set a cover background image on an element:

  .bg {Background: URL (Picture / Kities 1.JPG) no-repeat; Background size: cover; Background-position: center; Height: 200 pixels; }  

Right, CSS-only, the size of the element is actually a way to match the background image, like the image takes 100% width, and then takes the original aspect Higher height to fit the ratio?

Here is the playground:

As far as I know, CSS will never know about image size. However, what you can do, however, you can set the ratio of the image (height 56.25% width to padding-top or padding-bottom Are here).

Explanation

padding-top , when set as one percent, then reference the width of the element ( 100% ) in the form. 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; }
  & lt; Div class = "a" & gt; Hello & lt; / Div & gt; & Lt; Div class = "bg" & gt; & Lt; / Div & gt; & Lt; Div class = "c" & gt; By & lt; / Div & gt;  


No comments:

Post a Comment