Home > other >  Flex items dont shrink equally when padding is add to one of them
Flex items dont shrink equally when padding is add to one of them

Time:07-17

.flex-container {
  display: flex;
  width: 200px;
  height: 100px;
  padding: 10px;
  background-color: green;
}
.flex-item {
  min-width: 0;
  height: 100%;
  flex: 0 1 50%;
}
.flex-item-1 {
  margin-right: 50px;
  background-color: red;
}
.flex-item-2 {
  padding-left: 50px;
  background-color: rgb(15, 36, 221);
}
  <div >
    <div ></div>
    <div ></div>
  </div>

Flex items dont shrink equally when padding is add to one of them no matter what you do. Is it possible to make items grow equally or shrink equally if one of them have padding?

CodePudding user response:

Use CSS grid in this case

.flex-container {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  width: 200px;
  height: 100px;
  padding: 10px;
  gap: 50px;
  background-color: green;
}

.flex-item-1 {
  background-color: red;
}

.flex-item-2 {
  padding-left: 50px;
  background-color: rgb(15, 36, 221);
}
<div >
  <div ></div>
  <div ></div>
</div>

CodePudding user response:

I found an answer in beatifully written articles on css tricks - https://css-tricks.com/equal-columns-with-flexbox-its-more-complicated-than-you-might-think/

The conclusion is - padding and borders of flex items do not participate in flex-grow or flex-shrink calculations and act as they were taking space outside of those items.

CodePudding user response:

You can use aspect-ratio: 1 / 1

@import "https://cdn.jsdelivr.net/gh/KunalTanwar/normalize/css/normalize.inter.min.css";
body {
  height: 100%;
  display: grid;
  place-items: center;
}

.flex {
  width: 100%;
  color: white;
  height: 250px;
  display: flex;
  padding: 1rem;
  font-size: 2rem;
  column-gap: 1rem;
  max-width: fit-content;
  box-shadow: 0 0 0 1px blue;
}

.flex-item {
  width: 100%;
  height: 100%;
  aspect-ratio: 1/1;
}

.flex-item:first-child {
  background-color: red;
}

.flex-item:last-child {
  padding: 2rem;
  background-color: green;
}
<div >
  <div >
    without padding
  </div>

  <div >
    with padding
  </div>
</div>

  • Related