4

I'm using "container-fluid" and things work great for horizontal width-setting on columns using "span2", etc.

I have a unique requirement where I am representing things that I want to appear "square" while still enjoying the benefits of Bootstrap's responsive width-setting. Is there a good way for me to make sure my elements have the same height as their width?

blaster
  • 8,876
  • 11
  • 48
  • 77

3 Answers3

4

You can make an element with any aspect ratio you wish (height adjusts to the width) with the following padding trick (see jsfiddle):

  1. Outer DIV make the square space with vertical padding value as percentage of width.
  2. Inner DIV makes use of the outer DIV full size (padding space is normally not usable in outer).

HTML:

<div class="out">
  <div class="in">
  </div>
</div>

CSS:

.out {
  position: relative;
  height: 0;
  padding-bottom: 100%;
}
.in {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  background-color: red;
}
Marcin Skórzewski
  • 2,854
  • 1
  • 17
  • 27
1

Try the technique discussed in the following article:

http://alistapart.com/article/creating-intrinsic-ratios-for-video

I have my own poor-man's version of the above.

You define a container block with two child elements, an image and another block element:

<div class="sq-wrapper">
    <img class="spacer" src="http://placehold.it/100x100">
    <div class="content">Some content...</div>
</div>

Just create a lightweight image with the aspect ratio that you need.

Apply the following CSS:

.sq-wrapper {
    position: relative;
    display: inline-block;
    width: 100%;
    border: 1px solid gray;
}
.sq-wrapper .spacer {
    width: 100%;
    visibility: hidden;
    vertical-align: top;
}
.sq-wrapper .content {
    position: absolute;
    top: 0;
    left: 0;
    padding: 20px;
}

Give the .sq-wrapper a width of 100% and it will expand to fill its containing block.

Give the .spacer child element/image a width of 100% so that it will expand to fill the .sq-wrapper. Because the image has an intrinsic height, .sq-wrapper will shrink-to-fit the image because of the inline-block display type.

Use visibility: hidden to hide the image but preserve its space within the layout, and vertical-align: top to deal with the extra-whitespace-at-the-bottom issue.

Finally, take the .content out of the flow by using position: absolute.

You can see a demo at: http://jsfiddle.net/audetwebdesign/BQ2eJ/

The one thing to watch out for is that content could overflow if you shrink the window to a small enough size.

Reference

To learn how CSS computes the height of an inline replaced element, see:

http://www.w3.org/TR/CSS2/visudet.html#inline-replaced-height

Marc Audet
  • 46,011
  • 11
  • 63
  • 83
0

If you find this and are trying to make a background image keep its dimensions then use

background-size: contain;
Paul Roub
  • 36,322
  • 27
  • 84
  • 93