【发布时间】:2018-09-29 10:17:25
【问题描述】:
我在带有margin: 0 auto 的英雄图像上水平居中文本,但没有指定宽度。我在很多地方读到这个技巧只在指定宽度时才有效;为什么它在这种情况下有效?我的猜测是宽度只是设置为默认图像宽度。
这是我正在使用的代码(查看CodePen 以获取完整代码)。如果我从 .hero-image 的 CSS 规则集中删除除图像 URL 之外的所有内容,它仍然有效。
HTML:
<!-- Inside (Bootstrap 4) container-fluid div -->
<div class="row">
<div class="col">
<div class="hero-image">
<div class="hero-text text-white">
<h1>Natalie Cardot</h1>
<h5>Web developer</h5>
</div>
</div>
</div>
</div>
CSS:
.hero-image {
background-image: url(https://image.ibb.co/fzz87S/laptop_reversed.jpg);
/* Sets height to full height (100%) of viewport */
height: 100vh;
/* Ensures background image spans the full width of the viewport */
background-size: cover;
/* Aligns image to center of viewport */
background-position: center;
background-repeat: no-repeat;
/* Enables flex layout */
display: flex;
/* Vertically aligns (align-items defines how the browser distributes space between and around flex items along cross-axis of container; works like justify-content but in the perpendicular direction) */
align-items: center;
}
.hero-text {
margin: 0 auto;
}
【问题讨论】:
-
因为类
.container-fluid设置了宽度100% -
我删除了包含 .container-fluid 的 div,它仍然有效。
-
另外,如果宽度设置为 100%,margin: 0 auto 不应该居中;必须指定宽度,但必须小于 100% w3schools.com/css/css_align.asp
标签: css bootstrap-4