我正在尝试找到最有效的方法来将文本与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>


当前回答

非常简单的解决方案,我在我的项目中多次使用它:

源代码

.welcome_box{
    height: 300px;
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    border: solid 1px #dadada;
}

<div class="welcome_box">Hello Friends</div>

输出:

谢谢你提出这个问题。很高兴分享。

其他回答

我使用以下方法轻松地将随机元素垂直居中:

HTML格式:

<div style="height: 200px">
    <div id="mytext">This is vertically aligned text within a div</div>
</div>

CSS:

#mytext {
    position: relative;
    top: 50%; 
    transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
}

这将使我的div中的文本位于200px高的外部div的垂直中间。请注意,您可能需要使用浏览器前缀(如我的例子中的-webkit)来使其适用于您的浏览器。

这不仅适用于文本,也适用于其他元素。

您可以使用显示网格并将项目放置在中心:

.容器{宽度:200px;高度:200px;边框:纯红色;显示:栅格;放置项目:中心;}<div class=“container”>Lorem,ipsum dolor。</div>

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

display: flex;
align-items: center;

您可以通过将显示设置为“表格单元格”并应用垂直对齐: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.

嗯,显然有很多方法可以解决这个问题。

但我有一个绝对定位的<div>,高度:100%(实际上,顶部:0;底部:0,固定宽度),显示:表格单元格无法垂直居中文本。我的解决方案确实需要内部跨度元素,但我看到许多其他解决方案也需要,所以我不妨添加它:

我的容器是一个.label,我希望数字在其中垂直居中。我这样做是通过将绝对位置放在顶部:50%,并设置行高度:0

<div class="label"><span>1.</span></div>

CSS如下:

.label {
    position:absolute;
    top:0;
    bottom:0;
    width:30px;
}

.label>span {
    position:absolute;
    top:50%;
    line-height:0;
}

在行动中看到:http://jsfiddle.net/jcward/7gMLx/