首页 > 解决方案 > justify-content 没有预期的行为,我做错了什么?

问题描述

我想把一个放在页面中心h1div另一个下面。为此,我使用了以下 CSS 和 HTML:

.main {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100%;
  height: 100%;
}

h1 {
  display: flex;
  margin-block-start: 0;
  width: 40%;
}

.products {
  margin-top: 5rem;
  width: 40%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}
<!--
Commented because reactjs className does not work for snippet so replace by normal class

<div className="main">
  <h1>Products</h1>
  <div className="products">
  </div>
  -->
  
<div class="main">
  <h1>Products</h1>
  <div class="products">
  </div>

它们与列对齐,但未居中。

标签: javascriptcssreactjs

解决方案


在列方向弹性容器中时,需要align-items: center用于水平对齐。

.main {
   display: flex;
   flex-direction: column;
   align-items: center;
   width: 100%;
   height: 100%;
}

推荐阅读