I want to create a Flexbox with squares of fixed size. Solved with width % and padding-bottom %.
But if I put a picture in there, it changes the size.
How do I solve this?
I tried max-width, max-padding-bottom (lol i know), padding-bottom: max(x%), ...
I don't have any idea now.
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
.flex-container > div {
width: 32%;
padding-bottom: 32%;
position: relative;
background-color: #000;
margin: 0.5%;
}
img.flex {
height: 100%;
width: 100%;
}
<div class="flex-container">
<div>
<img class="flex" src="https://upload.wikimedia.org/wikipedia/commons/5/54/KDE_4.png">
</div>
<div></div>
<div></div>
</div>
<p> some text <p>
<p> some text <p>
<div class="flex-container">
<div></div>
<div></div>
<div></div>
</div>
From your code, the padding is also the room where you want the image to show.
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
.flex-container>div {
width: 32%;
padding-bottom: 32%;
position: relative;
background-color: #000;
margin: 0.5%;
}
img.flex {
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
}
<div class="flex-container">
<div>
<img class="flex" src="https://upload.wikimedia.org/wikipedia/commons/5/54/KDE_4.png">
</div>
<div></div>
<div></div>
</div>
<p> some text
<p>
<p> some text
<p>
<div class="flex-container">
<div></div>
<div></div>
<div></div>
</div>
You could also use a pseudo element to stretch your div to a square to avoid to make it use the whole space.
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
.flex-container::before {
content: "";
padding-bottom: 33.33%;
with: 0;
}
.flex-container>div {
width: 32%;
position: relative;
background: linear-gradient(45deg, rgba(255, 255, 255, 0.1)50%, transparent 50%) #000;
margin: 0.5%;
}
img.flex {
width: 100%;
max-height: 100%;/*might be better ? */
}
<div class="flex-container">
<div>
<img class="flex" src="https://upload.wikimedia.org/wikipedia/commons/5/54/KDE_4.png">
</div>
<div></div>
<div></div>
</div>
<p> some text
<p>
<p> some text
<p>
<div class="flex-container">
<div></div>
<div>d</div>
<div>d</div>
</div>
.flex-container {
display: flex;
flex-wrap: wrap;
justify-content: center;
width: 100%;
}
.flex-container>div {
width: 32%;
position: relative;
background-color: #000;
margin: 0.5%;
}
.flex-container>div::before {
content: '';
float: left;
width: 0;
padding: 50% 0;
}
img.flex {
height: 100%;
width: 100%;
}
<div class="flex-container">
<div>
<img class="flex" src="https://upload.wikimedia.org/wikipedia/commons/5/54/KDE_4.png">
</div>
<div></div>
<div></div>
</div>
<p> some text
<p>
<p> some text
<p>
<div class="flex-container">
<div></div>
<div></div>
<div></div>
</div>
if vertical padding or margin can be used to stretch a div using parent's width, you have also to mind the room used from the method.