为什么不将 justify-content: center 将 h2 和 #experience_content 项移动到 .experience 框的中心?[复制]

Why won't justify-content: center move the h2 and #experience_content items to the center of the .experience box? [duplicate]

提问人:WideRule 提问时间:11/8/2023 最后编辑:WideRule 更新时间:11/8/2023 访问量:36

问:

<html>
<head>
<style>
.experience {
    display: flex;
    flex-direction: column;
    justify-content: center;

}

.experience h2 {
    
}

#experience_content {
    display: flex;
    gap: 10px;

}
</style>
</head>
<body>

    <section class="experience">
            
        <h2>Work Experience</h2>
            
        <div id="experience_content">
            <img src=./images/supermarket.jpg width="260" height="195" alt=" shopping center">
                    
        <p> Please help me solve this stupid problem. I beg you.</p>
        </div>

    </section>

</body>
</html>

我尝试从 .experience 元素中删除 h2 元素。

我尝试了justify-content:以#experience_content元素为中心,但这对img和p元素也不起作用。

HTML 弹性框 CSS-选择器 证明

评论


答:

0赞 mandy8055 11/8/2023 #1

您面临的问题是,您正在使用 .该属性沿 flex 容器的主轴工作,在本例中,由于 .如果要水平居中,则需要使用在十字轴上起作用的属性,即 。justify-content: centerflex-direction: columnjustify-contentflex-direction: columnalign-items

<html>

<head>
  <style>
    .experience {
      display: flex;
      flex-direction: column;
      align-items: center;
      /* <-- Here */
    }
    
    .experience h2 {}
    
    #experience_content {
      gap: 10px;
    }
  </style>
</head>

<body>

  <section class="experience">

    <h2>Work Experience</h2>

    <div id="experience_content">
      <img src=./images/supermarket.jpg width="260" height="195" alt=" shopping center">

      <p> Please help me solve this stupid problem. I beg you.</p>
    </div>

  </section>

</body>

</html>