While trying to horizontally center text on a hero image, I used margin: 0 auto
without specifying a width. Surprisingly, this trick worked even though many sources claim it only works with a specified width. My theory is that the default image width may be in play here.
If you're curious, here's the code snippet I'm using (you can check out the full code on CodePen). Strangely enough, removing all CSS rules except for the image URL from the .hero-image
still produces the desired outcome.
HTML:
<!-- Part of the 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-imagine {
background-image: url(https://image.ibb.co/fzz87S/laptop_reversed.jpg);
/* Sets height to 100% of viewport */
height: 100vh;
/* Ensures background image covers entire width of viewport */
background-size: cover;
/* Aligns image at center of viewport */
background-position: center;
background-repeat: no-repeat;
/* Enables flex layout */
display: flex;
/* Vertically aligns content */
align-items: center;
}
.hero-text {
margin: 0 auto;
}