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


当前回答

使用CSS网格为我做到了:

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

其他回答

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

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

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

但我有一个绝对定位的<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/

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;
 }

您可以使用Flexbox在div内垂直对齐中心文本。

<div>
   <p class="testimonialText">This is the testimonial text.</p>
</div>

div {
   display: flex;
   align-items: center;
}

您可以在Flexbox完整指南中了解更多信息。

这是在CSS中使用calc()的div模式中div的另一种变体。

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

这是有效的,因为:

position:absolute用于在div中精确放置div我们知道内部div的高度,因为我们将其设置为20px。计算(50%-10px),用于对中内隔板高度的50%-一半