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


当前回答

您需要添加line-height属性,该属性必须与div的高度匹配。在您的情况下:

.中心{高度:309px;线条高度:309px;/*与高度相同*/}<div class=“center”>一行。</div>

实际上,您可能可以完全删除高度属性。

这只适用于一行文本,所以要小心。

其他回答

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

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

HTML

<div class="relative"><!--used as a container-->
    <!-- add content here to to make some height and width
    example:<img src="" alt=""> -->
    <div class="absolute">
        <div class="table">
            <div class="table-cell">
                Vertical contents goes here
            </div>
        </div>
    </div>
</div>

CSS

 .relative {
     position: relative;
 }
 .absolute {
     position: absolute;
     top: 0;
     bottom: 0;
     left: 0;
     right: 0;
     background: rgba(0, 0, 0, 0.5);
 }
 .table {
     display: table;
     height: 100%;
     width: 100%;
     text-align: center;
     color: #fff;
 }
 .table-cell {
     display: table-cell;
     vertical-align: middle;
 }

CSS:

.vertical {
   display: table-caption;
}

将此类添加到包含要垂直对齐的对象的元素中

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

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

使用显示器很容易:flex。使用以下方法,div中的文本将垂直居中:

第二部分{显示:-webkit flex;显示:柔性;对齐项目:居中;/*更多样式:*/高度:300px;背景色:#888;}<div>此处是您的文本。</div>

如果你愿意,水平:

第二部分{显示:-webkit flex;显示:柔性;对齐项目:居中;对齐内容:中心;/*更多样式:*/高度:300px;背景色:#888;}<div>此处是您的文本。</div>

您必须查看所需的浏览器版本;在旧版本中,代码不起作用。