Home > Enterprise >  How to align items in straight line using Flex and Space-between
How to align items in straight line using Flex and Space-between

Time:11-06

As can be seen in the image, when the width of first column increase, it pushes the contents of the second column also. I want the items of second column in straight line. One way of doing could be giving fixed width to first column, but I don't want to do this because, the count of columns is dynamic. Sometimes, there will be only three columns, so I will to increase width dynamically which I don't want to do.

enter image description here

#box { 
    display: flex;
    width: 100px;
    margin: 0 -5px;
}

.item {
    background: gray;
    width: 50px;
    height: 50px;
    margin: 0 5px;
}
<div id='box'>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
    <div class='item'></div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Demo: http://jsfiddle.net/GLpUp/

CodePudding user response:

You don't have to set an exact 'fixed' width, but try to set the width 'proportionally' with %.

When all divs have 100% they will all have the same width.

If you know your second column doesn't contain much content, simply reduce the percentage. Like this all columns will have the same width as their neighbours above or below them.

This would be a solution using flexbox. I agree with the comments, that using grid or table instead would be advisable.

#row { 
    display: flex;
    width: 100%;           
}

.item {
    width: 100%;
    height: 50px;    
    border: 1px solid teal;
}

.item:nth-of-type(2) {
    width: 30%;
}
<div id='row'>
    <div class='item'>I have a lot of content</div>
    <div class='item'>just 1</div>
    <div class='item'>...</div>
    <div class='item'>...</div>
</div>
<div id='row'>
    <div class='item'>This is a different length</div>
    <div class='item'>but</div>
    <div class='item'>the columns have the same</div>
    <div class='item'>widths as in row before</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related