我试图在div中水平居中显示一些文本。
CSS:
#parent {
background-color: #eee;
height: 48px;
text-align: center;
}
#colLeft {
background-color: #ff8b8b;
height: 48px;
display: inline;
float: left;
}
#colRight {
background-color: #c3d0ff;
height: 48px;
display: inline;
float: right;
}HTML:
<div id="parent" style="width:100%">
<div id="colLeft">left left left left</div>
Title
<div id="colRight">right</div>
</div>
<div style="width:100%; text-align:center">
Title - this one is really centered.
</div>但是考虑到#colLeft占用的空间,文本“标题”似乎居中,所以它并不是真正相对于浏览器宽度居中。
有没有一种方法可以让我真正将文本居中,不管#colLeft占用多少空间?
发布于 2012-12-17 05:59:26
并不推荐这样做,但您可以这样做:JS Fiddle。
#parent {
background-color: #eee;
height: 48px;
text-align: center;
}
#colLeft {
background-color: #ff8b8b;
height: 48px;
display: inline;
float: left;
}
#colRight {
background-color: #c3d0ff;
height: 48px;
display: inline;
float: right;
}
.title{
position: absolute;
width: 100px;
left: 50%;
margin-left: -50px;
}
<div id="parent" style="width:100%">
<div id="colLeft">left left left left</div>
<div class="title">Title</div>
<div id="colRight">right</div>
</div>
<div style="width:100%; text-align:center">Title - this one is really centered.</div>您可以将标题命名为position:absolute。给它一个宽度。left: 50%。margin-left:减去宽度的一半。它将保持在中心位置。但我并不建议你这么做...
发布于 2012-12-17 06:02:42
如果用div将Title括起来,如下所示:
<div style="position: absolute;left: 50%">Title</div>你在Webkit做得很好。
发布于 2012-12-17 06:23:30
<div align="left" style="border:5px solid white; text-align:center; position:relative">
<div align="left" style="border:4px solid brown; float:left; width:100px; position:absolute"><span>left</span></div>
<div align="left" style="border:4px solid brown; right:0; width:200px; position:absolute"><span>right</span></div>
<span>really centered</span></div>https://stackoverflow.com/questions/13905761
复制相似问题