我正在尝试找到最有效的方法来将文本与div对齐。我尝试了一些方法,但似乎没有一个有效。

.推荐文本{位置:绝对;左:15px;顶部:15px;宽度:150px;高度:309px;垂直对齐:中间;文本对齐:居中;字体系列:Georgia,“Times New Roman”,Times,serif;字体样式:斜体;填充:1em 0 1em 0;}<div class=“推荐文本”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。Duis aute irure多尔代表在voluptate velit esse cillum dolore eu fugiat nullapariator。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕。</div>


当前回答

这些天(我们不再需要InternetExplorer6-8),我只会使用CSS display:table(或display:flex)来解决这个问题。

表:.vcenter(.v中心){显示:表格;背景:#eee;/*可选的*/宽度:150px;高度:150px;文本对齐:居中;/*可选的*/}.vcenter>:第一个子级{显示:表格单元格;垂直对齐:中间;}<div class=“vcenter”><p>这是我的文本</p></div>

弯曲:.vcenter(.v中心){显示:柔性;对齐项目:居中;高度:150px;对齐内容:中心;/*可选的*/背景:#eee;/*可选的*/宽度:150px;}<div class=“vcenter”><p>这是我的文字</p></div>


对于较旧的浏览器:

这是(实际上是)我最喜欢的解决方案(简单且非常受浏览器支持):

第二部分{边距:5px;文本对齐:居中;显示:内联块;}.vcenter(.v中心){背景:#eee;/*可选的*/宽度:150px;高度:150px;}.vcenter:之前{内容:“”;显示:内联块;高度:100%;垂直对齐:中间;最大宽度:0.001%;/*为了防止文本换行,你不应该注意到它*/}.vcenter>:第一个子级{显示:内联块;垂直对齐:中间;最大宽度:99.999%;}<div class=“vcenter”><p>这是我的文字</p></div><div class=“vcenter”><h4>这是我的文本<br/>文本</br/>文本</h4></div><div class=“vcenter”><div><p>这是我的</p><p>文本</p></div></div>

其他回答

如果需要与min-height属性一起使用,则必须将此CSS添加到:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

您可以通过将显示设置为“表格单元格”并应用垂直对齐:middle;:

    {
        display: table-cell;
        vertical-align: middle;
    }

然而,根据我从中复制的摘录,这并非所有版本的Internet Explorer都支持http://www.w3schools.com/cssref/pr_class_display.asp未经许可。

注意:Internet Explorer 7和更早版本不支持值“内联表”、“表”、表标题、表单元格、表列、表列组、表行、表行组和继承”。Internet Explorer 8需要!DOCTYPE。Internet Explorer 9支持这些值。

下表显示了允许的显示值http://www.w3schools.com/cssref/pr_class_display.asp.

使用CSS网格为我做到了:

.外部{背景色:灰色;宽度:10rem;高度:10rem;显示:栅格;对齐项目:中心;}.内部{背景色:#FF8585;对齐自身:中心;}<div class='outer'><div class='inner'>所容纳之物</div></div>

一个不知道价值的简单解决方案:

HTML

<div class="main">
    <div class="center">
        whatever
    </div>
</div>

CSS

.main {
    position: relative
}

.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
    -moz-transform: translate(-50%, -50%);
    -o-transform: translate(-50%, -50%);
}

尝试一下,在父div上添加:

display: flex;
align-items: center;