Reputation: 20834
I have 3 blocks, that I need to:
I made something similar in some game engine:
But how can I achieve it with css?
I don't want to nest the inner divs because they're playing the same role.
I tried this but it doesn't work :(
* {
box-sizing: border-box;
}
.wrapper {
width: 100%;
display: flex;
position: relative;
}
.wrapper > * {
height: 300px;
display block;
}
.wrapper > *:nth-child(1) {
background-color: salmon;
width: 200px;
}
.wrapper > *:nth-child(2) {
background-color: khaki;
right: 50%;
}
.wrapper > *:nth-child(3) {
background-color: violet;
width: 50%;
}
<div class="wrapper">
<pre>
left: 0;
width: 200px;
</pre>
<pre>
left: 200px;
right: 50%;
</pre>
<pre>
left: 50%;
right: 0;
</pre>
</div>
Upvotes: 3
Views: 5946
Reputation: 1419
Try this
* {
box-sizing: border-box;
}
body{
display: flex;
flex-direction: row;
}
.wrapper, .wrapper-1 {
width: 50%;
display: flex;
position: relative;
}
.wrapper > *, .wrapper-1 > * {
height: 300px;
margin: 0;
display: inline;
white-space: nowrap;
}
.wrapper > *:nth-child(1) {
background-color: salmon;
flex-basis: 200px;
}
.wrapper-1 > *:nth-child(1) {
background-color: violet;
flex: 1 1 auto;
}
.wrapper > *:nth-child(2) {
background-color: khaki;
flex: 1 1 auto;
}
.wrapper > *:nth-child(3) {
background-color: violet;
flex: 1 auto;
}
<body>
<div class="wrapper">
<pre> flex-basis: 200px;
</pre>
<pre> flex: 1 1 auto;
</pre>
</div>
<div class="wrapper-1">
<pre>flex: 1 1 auto; </pre>
</div>
</body>
Upvotes: 2
Reputation: 42362
You can set flex: 0 0 50%
to the third child which means the element would not grow, shrink and will always occupy half the width of the flexbox container.
Now to allow the second child to occupy the remaining space left by the other two elements you can set flex-grow: 1
and set min-width: 0
(allows it to shrink further than its intrinsic width - note that default min-width
is auto for a flex item).
See demo below:
* {
box-sizing: border-box;
}
.wrapper {
width: 100%;
display: flex;
position: relative;
}
.wrapper > * {
height: 300px;
display: block;
}
.wrapper > *:nth-child(1) {
background-color: salmon;
width: 200px;
}
.wrapper > *:nth-child(2) {
background-color: khaki;
flex-grow: 1; /* grow width automatically if needed */
min-width: 0; /* allow shrinking below default width */
}
.wrapper > *:nth-child(3) {
background-color: violet;
flex: 0 0 50%; /* added */
}
<div class="wrapper">
<pre>
left: 0;
width: 200px;
</pre>
<pre>
left: 200px;
right: 50%;
</pre>
<pre>
left: 50%;
right: 0;
</pre>
</div>
Upvotes: 5