我的网站上有一个标题,这里有一个容器和三个div。
标题容器高100px。 第一个div浮动到左边,宽度为150px 第二个div浮动到右边,宽度为150px 第三个div在其中有另一个div,默认情况下会调整大小以填充剩余空间。
我希望第三个div垂直居中。当我添加display:table-cell和vertical-align:middle时,div会缩小到文本的大小。我只能使用固定大小调整div的大小。
<div id="#headingcontainer">
<div class="leftimg">Left</div>
<div class="rightimg">Right</div>
<div class="heading">Content to be centered horizontally and vertically</div>
</div>
#headingcontainer
{
border: none;
border-bottom: 2px solid #8c8cd4;
width: 100%;
height: 100px;
text-align: center;
background-color: #000;
margin-bottom: 10px;
margin-left: auto;
margin-right: auto;
}
div.heading
{
display: table-cell;
vertical-align: middle;
height: 100px;
text-align: center;
width: auto;
}
div.leftimg
{
width: 150px;
float: left;
}
div.rightimg
{
width: 150px;
float: right;
}
任何人都可以让我知道如何在不知道确切宽度的情况下将中间div居中?
如果我从标题类中取出显示:table-cell,它不再是垂直居中而是水平居中。
答案 0 :(得分:0)
我认为这可能是你正在寻找的......我改变了css中的div.header以在顶部填充,删除了table-cell并将边距设置为auto而不是width auto。看看这是否是你所希望的。您必须根据间距调整顶部的填充,但这对我来说似乎是最简单的方法。
#headingcontainer
{
border: none;
border-bottom: 2px solid #8c8cd4;
width: 100%;
height: 100px;
text-align: center;
background-color: #000;
margin-bottom: 10px;
margin-left: auto;
margin-right: auto;
}
div.heading
{
height: 100px;
text-align: center;
margin: auto;
padding-top:40px;
}
div.leftimg
{
width: 150px;
float: left;
}
div.rightimg
{
width: 150px;
float: right;
}
<div id="headingcontainer">
<div class="leftimg">Left</div>
<div class="rightimg">Right</div>
<div class="heading">Content to be centered horizontally and vertically</div>
</div>
答案 1 :(得分:0)
我现在找到了一个适合我的答案。
首先对HTML进行一些小改动(标题中有两个额外的div):
<div id="#headingcontainer">
<div class="leftimg">Left</div>
<div class="rightimg">Right</div>
<div class="heading"><div><div>Content to be centered horizontally and vertically<div></div></div>
</div>
然后转到CSS:
#headingcontainer
{
border: none;
border-bottom: 2px solid #8c8cd4;
background-color: #000;
margin-bottom: 10px;
width: 100%;
height: 100px;
}
div.heading
{
display: table;
border-collapse: collapse;
width: 100%;
height: 100px;
position: absolute;
}
div.heading div
{
display: table-row;
}
div.heading div div
{
display: table-cell;
text-align: center;
vertical-align: middle;
}
这允许最终div包含文本垂直居中和水平居中。帮助来自我在搜索后发现的另一个Stack Overflow问题 - 818725。
答案 2 :(得分:0)