html - 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;
}
编辑:不喜欢推荐问题的解决方案。我在下面选择的答案要容易得多。
解决方案
四个您可以使用的外部容器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>
推荐阅读
- php - 获取错误数据
- android - 如何在 Flutter 中实现实时人脸解锁功能
- c++ - 在 C++ 中减慢 SHA-256?
- c++ - std::set::emplace_hint() 实际上如何加速插入过程?
- docker - 如何设置端口以将静态网站作为 nginx docker 容器运行?
- php - 将图像从 localhost 传输到 cpanel Web 服务器的代码
- c# - 如何将浮点类型四舍五入到小数点后六位
- javascript - 奇怪的断点行为(移动到不同的位置,并且出现了更多的断点)
- jquery - flatpickr maxDate 配置
- java - 无法为 /com/sun/jna/win32-x86/jnidispatch.dll 库创建临时文件:系统找不到路径