1

我的网站上有一个标题,它有一个容器和三个 div。

标题容器高 100 像素。第一个 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 居中?

如果我从标题类中取出 display: table-cell 它不再垂直居中而是水平居中。

4

3 回答 3

0

我认为这可能是您正在寻找的...我将css中的div.header更改为顶部有填充,删除了表格单元并将边距设置为自动而不是宽度自动。看看这是否是你所希望的。您将不得不根据间距调整顶部的填充,但这对我来说似乎是最简单的方法。

#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>
于 2012-08-29T16:53:31.950 回答
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。

于 2012-08-30T12:46:48.110 回答
0

试试这个http://jsfiddle.net/KtgVN/20/

于 2012-08-30T13:33:16.857 回答