首页 > 解决方案 > HTML / CSS 在此示例中是否有更好/更清洁的水平和垂直居中方式?

问题描述

我是 HTML/CSS 新手,正在自己制作我的第一个网页。目前正在为 codecademy 做最后一个 CSS 项目。

我一直在摆弄这个很长时间,只是想不通。我正在尝试将所有元素集中在.mainContainer. 我猜“标题”应该与盒子在同一个容器中,但我不知道如何让它出现在盒子上方,所有东西都居中(x 和 y)。

下面是我能得到的最接近的。似乎框的底部居中,但我需要所有内容居中。我不明白为什么我有inline-block.mainContainer,但flex在.boxContainer。如果我删除一个,我会失去居中。我不认为我可以使用这样的多个显示器......那里发生了什么?

https://jsfiddle.net/ichristian/ce9mou4w/2/

HTML

<div class='mainContainer'>
  <h2>Title</h2>
  <div class='boxContainer'>
    <div class='box'>
      <p>Box 1</p>
    </div>
    <div class='box'>
      <p>Box 2</p>
    </div>
    <div class='box'>
      <p>Box 3</p>
    </div>
  </div>

</div>

CSS

.mainContainer{
    background-color: orange;
    height: 200px;
    width: 400px;
    align-items: center;
    text-align: center;
    display: inline-block;

}

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

.box {
  background-color: black;
  color: white;
  height: 40px;
  width: 40px;
}

.box + .box {
  margin-left: 40px;
}

编辑:不喜欢推荐问题的解决方案。我在下面选择的答案要容易得多。

标签: htmlcss

解决方案


四个您可以使用的外部容器flex-direction设置为column和内部容器设置为row

.mainContainer {
  display: flex;
  align-items:center;
  justify-content: center;
  flex-direction: column;
  background-color: orange;
  height: 200px;
  width: 400px;
}

h2 {
  margin: 0 0 20px 0;
}

.boxContainer {
  display: inherit;
  flex-direction: row;
}

.box {
  background-color: black;
  color: white;
  height: 40px;
  width: 40px;
  margin: 0 20px;
}
<div class='mainContainer'>
  <h2>Title</h2>
  <div class='boxContainer'>
    <div class='box'>
      <p>Box 1</p>
    </div>
    <div class='box'>
      <p>Box 2</p>
    </div>
    <div class='box'>
      <p>Box 3</p>
    </div>
  </div>

</div>

标题和它的同级容器最终可以使用 a 来分隔margin(例如元素margin-bottom上的a)。<h2>


推荐阅读