Flexbox垂直对齐无法正常工作

时间:2017-07-13 12:31:06

标签: html css flexbox vertical-alignment

现在我的div content只是水平居中对齐,但我的目标也是垂直对齐。我在Mac和iOS上使用Safari进行了测试,在Android上使用Chrome进行了测试。

这是我的CSS;

html, body {
    height: 100%;
}
body {
    background: #002560;
    background: linear-gradient(to bottom right, #002560, #0c182b);
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: 'Lato', sans-serif;
    color: white;
}

我的HTML看起来像这样;

<div style="display:flex;align-items:center;justify-content:center;" id="content">
    <div>
        <h1>I'd love to be centre aligned correctly.</h1>
    </div>
</div>

这是我在iOS(和其他平台)上看到的内容;

Screenshot of my webpage.

4 个答案:

答案 0 :(得分:2)

也许你可以增加身高。通常,在CSS中使用所有样式更容易。

html, body {
  height:100%;
}

.height-100 {
  height: 100%;
}

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

body {
    background: #002560;
    background: linear-gradient(to bottom right, #002560, #0c182b);
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: 'Lato', sans-serif;
    color: white;
}

  
<div class="height-100 center" id="content">
  <div>
        <h1>I'd love to be centre aligned correctly.</h1>
  </div>
</div>

答案 1 :(得分:0)

您忘了在 <yourpackage.SolomonTextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight=".6" android:gravity="center_horizontal" android:text="Match Summary" android:textColor="@color/white" /> div上添加height。查看下面的更新代码段...

#content
html, body {
    height: 100%;
}
body {
    background: #002560;
    background: linear-gradient(to bottom right, #002560, #0c182b);
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: 'Lato', sans-serif;
    color: white;
}
#content {
    height: 100%;
    width: 100%;
    text-align: center;
}

答案 2 :(得分:0)

您必须设置身高

&#13;
&#13;
html, body {
    height: 100%;
}
body {
    background: #002560;
    background: linear-gradient(to bottom right, #002560, #0c182b);
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: 'Lato', sans-serif;
    color: white;
}
&#13;
<div style="display:flex;align-items:center;justify-content:center;height:500px;width:100%;" id="content">
    <div>
        <h1>I'd love to be centre aligned correctly.</h1>
    </div>
</div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

使用flex-container的计算高度应用居中。在这种情况下,您应该明确地设置它(默认情况下,使用取内容的高度)。

body也可以是你的灵活容器。所以你可以删除额外的div包装器。

body {
    background: #002560;
    background: linear-gradient(to bottom right, #002560, #0c182b);
    margin: 0;
    background-repeat: no-repeat;
    background-attachment: fixed;
    font-family: 'Lato', sans-serif;
    color: white;
    
    height: 100vh;
    display: flex;
    
    /* Also you can apply this for common body layout */
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
<h1>I'd love to be centre aligned correctly.</h1>