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


当前回答

在网格项上自动边距。

与Flexbox类似,在网格项上应用自动边距会使其在两个轴上居中:

.container {
  display: grid;
}
.element {
  margin: auto;
}

其他回答

Flexbox非常适合我,将父div中的多个元素水平和垂直居中。

下面的代码将父div内的所有元素堆叠在一列中,并将元素水平和垂直居中。我使用子div将两个Anchor元素保持在同一行(行)上。在没有子div的情况下,所有三个元素(Anchor、Anchor和Paragraph)都堆叠在父div的列中。这里只有子div堆叠在父div列中。

.父div{高度:150px;显示:柔性;弯曲方向:柱;对齐内容:中心;背景:粉色;}<div class=“parent div”><div class=“child div”><a class=“footer link”href=“https://www.github.com/“>GitHub</a><a class=“footer link”href=“https://www.facebook.com/“>脸书</a><p class=“footer copywrite”>©2019 Lorem Ipsum</p></div></div>

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

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

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

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)来使其适用于您的浏览器。

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

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

检查此简单解决方案:

HTML

<div class="block-title"><h3>I'm a vertically centered element</h3></div>

CSS

.block-title {
    float: left;
    display: block;
    width: 100%;
    height: 88px
}

.block-title h3 {
    display: table-cell;
    vertical-align: middle;
    height: inherit
}

JSFiddle公司