2

I have a responsive column, which is then divided into 3 equal sub-columns.

I have an icon placeholder in each one with a width of 100%. Is there any way using CSS's flex to ensure that my height always equals what ever my computed width is?

I really want to avoid images and JavaScript if possible.

Steviewevie
  • 189
  • 1
  • 13

1 Answers1

1

There are two methods you could use. One is to set the height of the flexbox using vw. You could also use calc if needed. Of course if the page width becomes static on wider viewports or has a max-width set then you can use a media query to set the flexbox height in px, em etc.

The second method is to use padding on the flexbox child elements. Unlike margin, 100% top or bottom padding means 100% of the parent's width not height.

.flex {
    display: flex;
    background-color: red;
    margin-bottom: 1px;
}
.flex div {
    flex: 1;
    background: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIyOS4wMzE4MTMiIHZpZXdCb3g9IjAgMCAzMiAyOS4wMzE4MTMiPgo8ZyB0cmFuc2Zvcm09Im1hdHJpeCgwLjAzMTI1LDAsMCwwLjAzMTI1LDAsLTAuOTY4MTg3NSkiPgo8cGF0aCBkPSJNIDEwMjQsNTkwLjQ0NCA1MTIsMTkzLjAxOCAwLDU5MC40NDYgMCw0MjguNDA4IDUxMiwzMC45ODIgMTAyNCw0MjguNDEgWiBNIDg5Niw1NzYgbCAwLDM4NCAtMjU2LDAgMCwtMjU2IC0yNTYsMCAwLDI1NiAtMjU2LDAgMCwtMzg0IDM4NCwtMjg4IHoiLz4KPC9nPgo8L3N2Zz4K) center no-repeat;
    background-size: 50%;
}
.flex.vw {
    height: 16.67vw;
}
.flex.padding div {
    padding-top: 16.67%;
}
<div class="flex vw">
    <div></div>
    <div></div>
    <div></div>
</div>
<div class="flex padding">
    <div></div>
    <div></div>
    <div></div>
</div>
Michael Lawton
  • 1,460
  • 1
  • 14
  • 25