Search code examples
htmlcssflexbox

Responsive circles in a row with flexbox


I want to draw 4 circles, being all 4 flex-items, and I need them to scale with the container they are in. I have seen some solutions where padding-bottom is used, but I can´t really understand it.

I managed to get the result that I want with specific width and height in the flex-items. Can anyone do the same but without that and keeping the same structure in my HTML?

This is the fiddle.

.container {
  display: flex;
  flex-wrap: nowrap;
  width: 200px;
  height: 50px;
}
.holder {
  margin-right: 5px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
}
.h1 {
  background: blue;
}
.h2 {
  background: red;
}
.h3 {
  background: green;
}
.h4 {
  background: grey;
}
<div class="container">
  <div class="holder h1"></div>
  <div class="holder h2"></div>
  <div class="holder h3"></div>
  <div class="holder h4"></div>
</div>


Solution

  • Remove the fixed pixels on both the container and items, use percentage instead to make it responsive. You can still use px for margin and padding on the items, since it's under flexbox.

    Use a pseudo element with 100% of padding-top or padding-bottom, since padding is relative to the container's width, so that give you responsive equal width and height items.

    .container {
      display: flex;
    }
    .holder {
      flex: 1;
      margin: 1%;
      border-radius: 50%;
    }
    .holder:before {
      content: "";
      display: inline-block;
      padding-top: 100%;
    }
    .h1 {
      background: blue;
    }
    .h2 {
      background: red;
    }
    .h3 {
      background: green;
    }
    .h4 {
      background: grey;
    }
    <div class="container">
      <div class="holder h1"></div>
      <div class="holder h2"></div>
      <div class="holder h3"></div>
      <div class="holder h4"></div>
    </div>