user3616064
user3616064

Reputation: 43

How to apply remaining width to a div in the middle of 2 other divs

I'm trying to fill remaning area of screen with the second div, div 1 and 2 got fixed width. How could i achive this effect?

HTML

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>

Problem can be fixed by using this CSS code, when second div is set to auto it will fill remaning area left to be filled.

#div1 {
float:left;
width:400px;
height:200px;
background-color: gray;
}
#div2 {
float:right;
width:400px;
height:200px;
background-color: green; 
}
#div3 {
margin-left: 400px;
margin-right: 400px;
width:auto;
height:200px;
background-color: silver;
}

Edit

Upvotes: 3

Views: 97

Answers (5)

T J
T J

Reputation: 43156

Apply position: relative for their parent (if it is not positioned already) and apply the following to div2:

#div2{
    position:absolute;
    left:400px; /* width of div1 */
    right:400px; /* width of div3 */
    height:200px;
}

JSFiddle

You can use css3 calc() function if older browser support is not an issue.

#div2{
    display:inline-block;
    width: calc(100% - 800px); /*100% - width of div1 and div3 */
    height:200px;
}

JSFiddle

Upvotes: 1

Ankit Agrawal
Ankit Agrawal

Reputation: 6124

<style>
    .box{display: table;width: 100%;}
    #div1{width:400px; height:200px;background: #000;display: table-cell}
    #div2{width:auto; height:200px;background: #e6e6e6;display: table-cell}
    #div3{width:400px; height:200px;background: #000;display: table-cell}
</style>

<div class="box">
    <div id="div1"></div>
    <div id="div2">ds</div>
    <div id="div3"></div>
</div>

Upvotes: 1

Nico O
Nico O

Reputation: 14102

Classically, this would look like this:

CSS:

#div1 {
    float:left;
    width:400px;
    height:200px;
    background-color: gray;
}
#div2 {
    margin-left: 400px;
    margin-right: 400px;
    width:auto;
    height:200px;
    background-color: silver;
}
#div3 {
    float:right;
    width:400px;
    height:200px;
    background-color: green;
}

HTML:

<div id="div1"></div>
<div id="div3"></div>
<div id="div2"></div>

DEMO: http://jsfiddle.net/NicoO/5AJkn/

P.S: expand your screen > 800px to prevent the layout from breaking. Could also be solved by adding a min-width to a new parent element.

Upvotes: 4

Luan Nico
Luan Nico

Reputation: 5917

If your browser support calc, you coudl try:

#div2 { float:left; width:calc(100% - 800px); height:200px; }

Add the margins too, if any.

Upvotes: 1

Related Questions