Reputation: 479
I have 3 divs. One div is centered and 2 divs located from left and right sides. The centered div has max-width of 400 px. Here is the CSS
#left{float: left;background-color: red;height:100%;}
#right{float: right;background-color: green;height:100%}
#center{max-width:400px;margin: auto;background-color: blue;height:100%}
#container{width:100%;height:50px;}
body{color:white;}
and here is the HTML
<div id='container'>
<div id='left'>
left
</div>
<div id='right'>
right
</div>
<div id='center'>
center
</div>
</div>
I also prepared a jsfiddle. I need left and right divs to be "stretched" to center div.
Upvotes: 1
Views: 774
Reputation: 105903
if you have nothing against using flex, it will make it easy.
Below without reordering your HTML structure but using order
in CSS to set #center
at center
:) .
#container {
display: flex;
}
#container > div {
flex: 1;
order: 1;
background:yellow;
}
#container > div#center {
max-width: 400px;
order: 2;
/* let'see it */
background: linear-gradient(to left, gray 50%, lightgray 50%) left no-repeat;
border: solid;
background-size: 398px auto;/* show the last 2 pixel blank when max-width reached */
}
#container > div#right {
order: 3
}
<div id='container'>
<div id='left'>
left
</div>
<div id='right'>
right
</div>
<div id='center'>
center
</div>
</div>
Upvotes: 2
Reputation: 5564
You can use the calc()
function.
Specifically:
width: calc(50% - 200px);
Since the width of the center element is 400px and both sides are equal, you can simply calculate the width for both sides by taking 50% of the total width minus 200px (representing half of the center element). This gets you the width between the viewport edge and the edge of the center element.
Can I Use support table for calc().
Try it out below:
#left {
float: left;
background-color: red;
height: 100%;
width: calc(50% - 200px);
}
#right {
float: right;
background-color: green;
height: 100%;
width: calc(50% - 200px);
}
#center {
max-width: 400px;
margin: auto;
background-color: blue;
height: 100%
}
#container {
width: 100%;
height: 50px;
}
body {
color: white;
}
<div id='container'>
<div id='left'>
left
</div>
<div id='right'>
right
</div>
<div id='center'>
center
</div>
</div>
Upvotes: 1
Reputation: 8537
You can do that with calc()
function :
#left{float: left;background-color: red;height:100%; width: calc(50% - 200px);}
#right{float: right;background-color: green;height:100%; width: calc(50% - 200px);}
200px
represents half of the center width container and 50%
because there are two containers of each side (left and right)
Upvotes: 1