两个浮动的div,中间有灵活的div

时间:2012-08-09 18:27:41

标签: css layout html css-float

我需要在固定宽度的标题中添加以下内容:

  1. 不同宽度的div向左浮动。
  2. 不同宽度的div向右浮动。
  3. h2位于它们之间,占据任何剩余空间。
  4. 浮动div包含的内容可能会有所不同。

    我尝试了各种方法,但都失败了。我知道一个解决方案是绝对定位外部div,然后将h2拉伸到整个宽度并使文本居中,使其位于中央,但必须有一个更好的方法来做到这一点。

4 个答案:

答案 0 :(得分:9)

基本 jsFiddle example ,标记最少。

<强> 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;
} 

答案 1 :(得分:4)

您可以使用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

答案 2 :(得分:2)

考虑以下HTML:

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

CSS代码:

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

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

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

演示:http://jsfiddle.net/MAhmadZ/pMfLx/

答案 3 :(得分:1)

试一试 我认为它可以解决你的问题

<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>