首页 > 解决方案 > 无法让 flexbox 在中心垂直对齐我的内容

问题描述

我刚开始学习 HTML 和 CSS 并遇到了 justify-content 不会垂直居中我的元素的问题。我的 flex-direction 是 column ,即使它作为默认行并使用 align-items 我的元素也不会垂直移动,但水平它总是有效的。我真的只是想使用 flex 将文本垂直和水平居中。我也在使用 Firefox,我也在 Chrome 上进行了测试。这是HTML

<div class="brands">
    <section class="YSL">
        <h1>Yves Saint Laurent</h1>
    </section>

    <section class="LV">
        <h1>Louis Vuitton</h1>
    </section>
</div>

这是我的元素CSS:

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

.YSL{
    color: black;
    margin: 0;
}

.LV{
    color: black;
    margin: 0;
}

标签: htmlcssflexbox

解决方案


您需要稍微更改您的 HTML 和 CSS。

我认为这正是您想要的,如果有什么我可以改进的,请告诉我:

html,
body {
  height: 100%;
}

body {
  margin: 0;
}

.brands {
  height: 100%;
  padding: 0;
  margin: 0;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.row {
  border: 1px solid #000000;
}
<div class="brands">
  <div class="row">
    Yves Saint Laurent
  </div>
  <div class="row">
    Louis Vuitton
  </div>
</div>


推荐阅读