好吧,我认为网格与中心完美对齐,却发现它偏离了几个像素。我完全放弃了所有居中尝试并在线查看但找不到任何东西。
我知道我可以使用 CSS 网格、Flexbox 等,但我正在尝试学习如何在不使用任何帮助的情况下创建网站。这样我就可以了解事物背后的原因。
fiddle :
https://jsfiddle.net/8L9ye7nj/5/
网格 HTML:
<div class="box-wrapper">
<div class="box-container">
<div class="box" id="stethoscope">
<div class="box-label">
<p>Book an appointment</p>
</div>
</div>
<div class="box" id="prescription">
<div class="box-label">
<p>Request a repeat prescription</p>
</div>
</div>
<div class="box" id="group">
<div class="box-label">
<p>Join the Patient Group</p>
</div>
</div>
</div>
</div>
网格 CSS:
.box {
float: left;
width: 25%;
height: 300px;
background-color: #252625;
color: #FFF;
position: relative;
padding: 15px;
margin: 0.5%;
}
.box-label {
position: absolute;
bottom: 0;
text-align: center;
background-color: rgba(0,0,0,0.5);
width: 100%;
padding: 7px 0;
left: 0;
}
.box-label:hover {
animation: box-stretch 1s forwards ease-in-out;
cursor: pointer;
}
.box-container {
width: 90%;
}
.box-container::after {
content: "";
clear: both;
display: table;
}
.box-wrapper {
background-color: #B21645;
padding: 30px;
}
最佳答案
如何划分盒子并将它们居中?
您可以使用 calc使用数学表达式计算 CSS 中的高度、宽度等。您可以在此处将框的宽度除以三。
.box {
display: inline-block;
width: calc(100% / 3);
}
需要考虑的事项
注意行内 block 元素之间的空间。你可以阅读更多关于 那here .
尽可能避免使用 float 。大多数使用 float 完成的布局都可以使用 inline-block 实现。 float 只是为了获取一个元素,把它放在一边,让其他内容在它周围流动。就这些。
box-wrapper
和box-container
中的一个只需要将内容包裹起来。
代码片段
body {
margin: 0;
padding: 0;
}
* {
box-sizing: border-box;
}
.box-wrapper {
background-color: #b21645;
padding: 20px;
}
.box {
position: relative;
display: inline-block;
width: calc(100% / 3);
padding: 0 10px;
height: 300px;
overflow: hidden;
}
.box img {
height: 100%;
width: 100%;
object-fit: cover;
object-position: left top;
}
.box-label {
position: absolute;
bottom: 0;
width: calc(100% - 20px);
text-align: center;
background-color: rgba(0, 0, 0, .6);
padding: 10px 0;
transition: padding 0.3s;
}
.box-label:hover {
padding: 25px 0;
}
.box-label p {
font-family: Helvetica;
color: white;
font-size: 20px;
}
<div class="box-wrapper">
<div class="box">
<img src="https://images.unsplash.com/photo-1509027572446-af8401acfdc3?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ef8f839186c5a6055d2802005b575194&auto=format&fit=crop&w=500&q=60" alt="" />
<div class="box-label">
<p>Some Title Here</p>
</div>
</div><div class="box">
<img src="https://images.unsplash.com/photo-1509027572446-af8401acfdc3?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ef8f839186c5a6055d2802005b575194&auto=format&fit=crop&w=500&q=60" alt="">
<div class="box-label">
<p>Some Title Here</p>
</div>
</div><div class="box">
<img src="https://images.unsplash.com/photo-1509027572446-af8401acfdc3?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=ef8f839186c5a6055d2802005b575194&auto=format&fit=crop&w=500&q=60" alt="">
<div class="box-label">
<p>Some Title Here</p>
</div>
</div>
</div>
关于html - 如何在不使用 CSS Grid 或 flexbox 的情况下将网格完美地居中放置在容器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52227746/