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

其他回答

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

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

如果你愿意,水平:

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

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

HTML格式:

<div class="col-md-2 ml-2 align-middle">
    <label for="option2" id="time-label">Time</label>
</div>

CSS:

.align-middle {
    margin-top: auto;
    margin-bottom: auto;
}

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

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