Home > Net >  CSS Flexbox with Margin Spacing Causing Unwanted Stretch of Items
CSS Flexbox with Margin Spacing Causing Unwanted Stretch of Items

Time:09-28

I've got a flexbox. There are 4 circles that are 25% width of the parent element. I added margin between the items but now the circles "stretch" because of my padding %. I'd like to keep the padding as a % to maintain an aspect ratio I require. But when I add margin to create spacing between the items stretch.

.items {
  display: flex;
  flex-wrap: wrap;
}

.items>* {
  flex: 1;
  flex-basis: 25%;
}

.items>*:after {
  content: '';
  display: block;
  background: #000;
  margin: 5px;
  padding-bottom: 100%;
  border-radius: 50%;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

The shape I want, but not the spacing:

With margin spacing:

The spacing I want, but not the shape:

enter image description here

Also, the reason I use margin is to have equal spacing all around the element in the case there are rows of elements.

How do I get the spacing and shape I want together?

CodePudding user response:

Insert a gap in your flex element, then remove the padding and margin for the pseudoelement (::after) and use aspect-ratio

.items {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px;
}

.items > * {
  flex: 1;
  flex-basis: 25%;
}

.items > *::after {
  content: '';
  display: block;
  background: #000;
  aspect-ratio: 1;
  border-radius: 50%;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

CodePudding user response:

Why not remove the margin from the :after pseudo element and use padding on the main element? (also added box-sizing on main element):

.items {
  display: flex;
  flex-wrap: wrap;
}

.items>* {
  flex: 1;
  flex-basis: 25%;
  padding: 5px;
  box-sizing: border-box;
}

.items>*:after {
  content: '';
  display: block;
  background: #000;
  padding-bottom: 100%;
  border-radius: 100%;
}
<div >
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

  • Related