Proportional scaling of responsive boxes using just CSS

Skriven av

Stefan_Singer

Stefan Singer

Having fluid width squares or rectangles (any kind of “box” you like actually) has always been a problem with responsive or fluid width sites.
How do you specifiy the height of an element as a percentage of the width of the very same element without using javascript wizardry?

Here’s an example of what result we want, and the result most people are used to without resorting to using javascript:

CSS

.imageContainer {
  position: relative;
  width: 25%;
  padding-bottom: 25%;
  float: left;
  height: 0;
}

img {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
}

HTML

<div class="imageContainer">
  <img src="/save/http://placekitten.com/250/250" />
</div>

The reason this actually works is that padding in percent IS based on the elements width. So it turns out you actually CAN set the height of an element relative to its own width.

For a simple working example with four ultra-cute placekittens, see this basic fiddle.

And yes, the only reason for the different image sizes in the fiddle is to get an unique ultra-mega-cute kitten for each image.

Implementing basic HTTP authentication for HTTP requests in AngularJS

Do you need to send basic HTTP authentication headers with your requests from AngularJS? Maybe for c...

Föregående inlägg