对齐内容不在div居中

时间:2020-06-02 21:54:45

标签: html css

我想使用align-content center将黑色div居中,但它没有居中。

.container{
    background-color:red;
    width:100%;
    height:300px;

    flex-wrap: wrap;
    align-content:center;
}

.flex{
    display: flex;
    width:30%;
    height:30px;
    background-color:black;
}
<div class="container">
    <div class="flex"></div>
</div>

enter image description here

https://ibb.co/fXGb6j2

1 个答案:

答案 0 :(得分:0)

您将规则分配错了。 .container必须具有display: flex;而不是容器的子代。它必须是justify-content: center;而不是align-content: center;

  • justify-content: center;导致水平居中
  • align-items: center;导致垂直居中

.container {
  display: flex;
  width: 100%;
  height: 300px;
  justify-content: center;
  align-items: center;
  background-color: red;
}

.flex {
  width: 30%;
  height: 100px;
  background-color: black;
  color: white;
}
<div class="container">
  <div class="flex">I am centered!</div>
</div>