问题
I know the squared solution with :before { padding-bottom }
. This works only with a width value, because padding is always using a relation to the parents width. - But exactly this is my problem.
I ONLY have the value of the a fixed HEIGHT (by parent container) and I need squared boxes by that height value. I don't like to use JS. If there is a solution to REPLACE the STATIC WIDTH value with pure CSS, please tell me!
Here's a simple code sample:
div.wrapper {
height: 70px;
padding: 5px;
background: black;
}
div.box {
float: left;
width: calc(70px - 10px); /* here is that static value for width, but better would be a relation to (parent) height */
height: calc(100% - 10px);
margin: 5px;
}
div.box.b1 {
background: orange;
}
div.box.b2 {
background: red;
}
div.box.b3 {
background: green;
}
div.box.b4 {
background: dodgerblue;
}
div.box.b5 {
float: right;
background: grey;
}
<div class="wrapper">
<div class="box b1">A</div>
<div class="box b2">B</div>
<div class="box b3">C</div>
<div class="box b4">D</div>
<div class="box b5">E</div>
</div>
I also was looking for the "css-3 grid", but I didn't found a good solution. But if anyone know about thet problem, please tell me! :)
PS: Just for info... The width of the parent is always 100% (or vw). I want to create a navbar with a defined height, which may be changed via media queries. But only the height value, never the width value of the parent container.
PPS: I found some more question here about that problem, but nobody understood the enquirers. Because we are not looking for "var height = width", we're looking for "var width = height". ;)
回答1:
Okay, I found a way with grid and css-vars...
:root {
--box-spacing: 10px;
--box-length: 60px;
}
.grid {
display: grid;
grid-template-columns: repeat(4, var(--box-length)) auto var(--box-length);
grid-auto-rows: var(--box-length);
grid-template-areas:
"a b c d . e";
grid-gap: var(--box-spacing);
padding: var(--box-spacing);
background:black;
}
.grid > :nth-child(1) {
grid-area: a;
background:orange;
}
.grid > :nth-child(2) {
grid-area: b;
background:red;
}
.grid > :nth-child(3) {
grid-area: c;
background:green;
}
.grid > :nth-child(4) {
grid-area: d;
background:blue;
}
.grid > :nth-child(5) {
grid-area: e;
background:grey;
}
<div class="grid">
<div>A</div>
<div>B</div>
<div>C</div>
<div>D</div>
<div>E</div>
</div>
I simply use the same var() for width and width lengths. And grid-template-areas
allows it to use .
for an empty column at the fifth position. That column has an auto width.
It's not beauty, but it works... if you've a better solution, tell me! :)
来源:https://stackoverflow.com/questions/56326810/squared-boxes-by-height-not-width-to-create-equal-width-aspect-ratio