我需要在固定宽度的标题中添加以下内容:
浮动div包含的内容可能会有所不同。
我尝试了各种方法,但都失败了。我知道一个解决方案是绝对定位外部div,然后将h2拉伸到整个宽度并使文本居中,使其位于中央,但必须有一个更好的方法来做到这一点。
答案 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;
}
答案 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>