Two floating divs with a flexible div between

I need the following in a fixed-width header:

  • The division of variable width moves to the left.
  • The division of variable width moves to the right.
  • h2, centered between them, which occupies any remaining space.

Floating divs contain content that may vary in size.

I tried different approaches, but they all failed. I know that one solution is to completely position the outer divs and then stretch h2 to the full width and center the text so that it sits centrally, but there should be a nicer way to do this.

+5
source share
4 answers

Basic jsFiddle example with minimal markup.

HTML

<div id="container">
    <div id="left">left</div>
    <div id="right">right</div>
    <h2>H2</h2>
</div>

CSS

#container {
    border:1px solid #999;
}
#left {
    float:left;
}
#right {
    float:right;
}
h2 {
    text-align:center;
    margin:0;
} 

+9

display: inline-block float, CSS calc, div:

HTML:

<div id="wrapper">
    <div id="one"></div><div id="two"></div><div id="three"></div>
</div>

CSS

#wrapper {
    min-width: 300px;
}
#one, #two, #three {
    display: inline-block;
    height: 300px;
}
#one {
    background: lightgreen;
    width: 100px;
}
#two {
    background: lightblue;
    width: 100%;
    width: calc(100% - 300px);
    width: -webkit-calc(100% - 300px);
    width: -moz-calc(100% - 300px);
}
#three {
    background: lightgreen;
    width: 200px;
}​

jsFiddle Demo

h2 div, #two.

+4

Given the following HTML:

<div id="parent">
    <div id="left">Left</div>
    <h2>Heading</h2>
    <div id="right">Right</div>
</div>

CSS code:

#parent {
    width: 80%;
    margin: auto;
    display: table;
}

#parent div, #parent h2 {
    display: table-cell;  
}

#left, #right {
    width: 50px;
}

Demo: http://jsfiddle.net/MAhmadZ/pMfLx/

+2
source

try this i think this can solve your problem.

<style type="text/css">
div{
display: inline-block;
vertical-align: top;
height: 50px;
border: 1px solid red;
position: static;
}

#one{
float: left;
width: 100px;
}

#three{
float: right;
width: 100px;
}
</style>

<div id="outerDiv" style="width: 500px;height: 500px;border: 1px solid red;">

    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>
</div>

<script type="text/javascript">
var spaceLeft = document.getElementById("one").offsetWidth;

var spaceRight = document.getElementById("three").offsetWidth;

var totalSpace = document.getElementById("outerDiv").offsetWidth;

document.getElementById("two").style.width = totalSpace-(spaceLeft+spaceRight+4) + "px";
</script>
0
source

All Articles