我使用margin: 0 auto
在英雄图像上水平居中文字,但没有指定宽度。我在很多地方读过这个技巧只有在指定宽度时才有效;为什么它在这种情况下工作?我的猜测是宽度只是设置为默认图像宽度。
这是我正在使用的代码(查看完整代码的CodePen)。如果我从.hero-image
的CSS规则集中删除除了图像网址之外的所有内容,它仍然有效。
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;
}
答案 0 :(得分:0)
Margin:0
, font-size
自动生效
我建议你让英雄文字的宽度为100%。使用text-align:center;
时,始终将文本居中。
我的最终守则
.hero-text {
margin:0px;
width:100%;
text-align:center
}
答案 1 :(得分:0)
文本居中,因为您有body { text-align: center }
。英雄文本div的宽度不是浏览器窗口的整个宽度的原因是因为.hero-image
是display: flex
。要使汽车保证金做某事,div必须小于100%宽。它是,所以它可以工作,但你真的不需要它,因为居中的文本为你做。
如果您移除display: flex
,那么您会看到.hero-image
变为100%宽,并且您的自动边距无效,因为没有可用于L / R边距的空间(请注意,文字仍然居中,因为text-align)。
答案 2 :(得分:0)
这里不是关于经典的margin:auto
,而是关于flexbox。您的容器设置为display:flex
,而.hero-image
是一个弹性项目,其宽度不再是100%,就像默认div一样,但它是相同的其内容的大小以及为什么margin:auto
将您的元素集中在您不需要指定固定宽度的原因。
一些相关问题:
What's the difference between margin:auto and justify-content / align-items center?