Reputation: 171
I need a css flex way to set 2 items per row and in each row the second item to expand with width auto.
I tried a lot of things, like setting margin-right:auto for second item in each row, but is not working.
Here is what I have now:
div{
display:flex;
flex-wrap:wrap;
}
div span{
background:red;
margin:2px;
white-space:nowrap;
}
div span:nth-child(2),
div span:nth-child(4),
div span:nth-child(6){
flex-basis:100%;
background:yellow;
}
<div>
<span>aaa</span>
<span>bbbbbb</span>
<span>ccccccccc</span>
<span>ddd</span>
<span>eee</span>
<span>fff</span>
</div>
The text inside a flex item should not wrap.
Here is the result I need:
Upvotes: 1
Views: 445
Reputation: 371183
This layout can't work with Flex, because each row is independent from other rows, and column widths cannot be defined.
However, the solution is simple with Grid, because column widths can be defined.
div {
display: grid;
grid-template-columns: min-content 1fr;
}
div span {
background: red;
}
div span:nth-child(2),
div span:nth-child(4),
div span:nth-child(6) {
background: yellow;
}
<div>
<span>aaa</span>
<span>bbbbbb </span>
<span>ccccccccc</span>
<span>ddd</span>
<span>eee</span>
<span>fff</span>
</div>
In the code above, grid-template-columns
defines two columns.
The first is set to width min-content
, which means it will size to the minimum width possible.
The second is set to 1fr
, which means it will take all remaining space.
Upvotes: 2
Reputation: 233
.item {
width: 100%
}
.container {
display: flex;
flex-wrap: wrap;
}
.container > span {
flex: 50%; /* or - flex: 0 50% - or - flex-basis: 50% - */
margin-bottom: 10px;
}
span:nth-child(odd) {
background-color: red;
}
span:nth-child(even) {
background-color: yellow;
}
<div class="container">
<span class="item">aaa</span>
<span class="item">bbbbbb</span>
<span class="item">ccccccccccccccccccccccccccccccccccccc</span>
<span class="item">ddd</span>
<span class="item">eee</span>
<span class="item">fff</span>
</div>
Upvotes: 0
Reputation: 7447
Updated with no wrap for text
Here is a quick example, which hopefully achieves the desired result.
It works on the posted HTML structure, just made some changes on CSS in <style>
.
Example: (see it in live with the button below)
<style>
div {
/* 👇 edit left span width here */
--left-span-width: 150px;
/* 👇 edit gap of span here */
--span-gap: 2px;
display: flex;
flex-wrap: wrap;
gap: var(--span-gap);
}
div span:nth-child(odd) {
width: calc(var(--left-span-width) - var(--span-gap));
background: red;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
div span:nth-child(even) {
flex: 1 1 calc(100% - var(--left-span-width));
background: yellow;
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
</style>
<div>
<span>aaa</span>
<span>bbbbbb</span>
<span>ccccccccc ccccccccc ccccccccc</span>
<span>ddd</span>
<span>eee</span>
<span>fff</span>
</div>
Upvotes: 1