user2265529 user2265529 - 6 months ago 10
HTML Question

3 divs: one centered div with max-width and left,right divs that should take the remaining space

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.

Answer

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>

Comments