Nick Nick - 3 months ago 10
CSS Question

How to align 2 div in the same lines without one of the div having a width

On some webpages I have created a main div called middlewrapper and these contains two divs inside left and middle. The left div is only used on certain pages and will only use up the required spacing while the middle wrapper use up the remaining spacing of the middlewrapper. While on other pages when left is not being used, middle is being used and it is using up 100% of middlewrapper

A working example is provided



#middlewrapper { width: 1100px; margin: 0 auto; padding: 0; border: 0px solid #bbbbbb; background: #ffffff; overflow: hidden; }
#left { float: left; width: 19%; margin: 0 6% 0 0; vertical-align: top; background: green; height: 100px; }
#middle { width: auto; padding: 0; background: #ffffff; min-height: 100px; overflow: hidden; background: red; height: 100px; }

<div id="middlewrapper">
<div id="left">
Test Left
</div>

<div id="middle">
Test Middle
</div>
</div>





However now I want to create a div called middle and right and want to naturally push the div to the right. However, I'm not having any luck since no matter what I do I always seem to have the
div
in 2 separate lines.

A working example is provide



#middlewrapper { width: 1100px; margin: 0 auto; padding: 0; border: 0px solid #bbbbbb; background: #ffffff; overflow: hidden; }
#middle { width: auto; padding: 0; background: #ffffff; min-height: 100px; overflow: hidden; background: red; height: 100px; }
#right { float: right; width: 19%; margin: 0 0 6%; vertical-align: top; background: blue; height: 100px; }

<div id="middlewrapper">
<div id="middle">
Test Middle
</div>
<div id="right">
Test Right
</div>
</div>




Answer

#middlewrapper	{ 
    width: 1100px; 
    margin: 0 auto; 
    padding: 0; 
    border: 0px solid #bbbbbb; 
    background: #ffffff; 
    overflow: hidden; 
    display: flex; // to make the children align
}

#middle { 
    flex: 1; // stretch to the available width
    width: auto;  
    padding: 0; 
    background: #ffffff; 
    min-height: 100px; 
    overflow: hidden; 
    background: red; 
    height: 100px; 
}
#right { 
    width: 19%; 
    background: blue; 
    height: 100px; 
}
<div id="middlewrapper">
    <div id="middle">Test Middle</div>
    <div id="right">Test Right</div>
</div>

Here's how you do it with flexbox. You need to put flex grow in red container to be able to get the spare space.

Comments