I horizontally centered text on a hero image with margin: 0 auto
but without specifying width. I've read in a bunch of places that this trick only works when width is specified; why is it working in this case? My guess is the width is simply set to the default image width.
Here's the code I'm using (view CodePen for full code). If I remove everything but the image URL from the CSS ruleset for .hero-image
, it still works.
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;
}