How does setting margin: 0 auto horizontally center text on an image when no width is defined?

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;
}

Answer β„–1

Forget about the old-school margin:auto trick, it's all about flexbox now. By setting your container with display:flex, the .hero-image becomes a flex item whose width is not limited to 100%, but adjusts to the size of its content. That's why using margin:auto will automatically center your element without needing to specify a fixed width.

If you're curious, check out these related questions:

Diving into the differences between margin:auto and justify-content / align-items center

Exploring the relationship between flex item width, flex-direction: column, and margin: 0 auto

Answer β„–2

Margin:0 auto is effective due to the default font-size. I highly recommend setting the hero-text width to 100% and using text-align:center; for perfect text alignment. Here is my final code:

.hero-text {
    margin:0px;
    width:100%;
    text-align:center
}

Answer β„–3

The reason why the text is perfectly centered is due to the CSS rule body { text-align: center }. The width of the hero text div appears narrower because of the .hero-image class with display: flex. When the width is less than 100%, the auto margin works as intended, although it may not be necessary since the text is already centered.

If you were to remove the display: flex property from the .hero-image class, you would notice that the div stretches to 100% width and the auto margin becomes ineffective without any horizontal space for margins (note that the text remains centered due to text-align).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a dynamic logo image in a Bootstrap 4 navbar that seamlessly overlaps while maintaining full responsiveness is a simple yet effective way to elevate

Is it possible to create a responsive overlapping logo on a Bootstrap navbar without affecting the hamburger menu icon? Good day! I am currently using Laravel Spark along with Bootstrap for my project, and I have encountered a specific challenge: How ca ...

The HTML link is not directly attached to the text, specifically in Internet Explorer

When viewing my website in Chrome, the menu links in the Header function correctly. However, in Internet Explorer (specifically version 11), hovering over 'HOME,' 'LISTINGS,' or 'AGENTS' reveals that the displayed URL is incor ...

Influence of scoped styles on external webpages

I'm facing an issue with my nuxt app where I have two pages, each with different background styles. However, the background of one page is overriding the other. index.vue <style scoped> body { background-color: #ffffff; } #banner { backgr ...

Modifying alignment of buttons in React components

Transforming the typical Tic Tac Toe game from the React tutorial, with an added one-player feature. Oddly, button alignment shifts out of place once a value is inserted; causing the button to drop by about 50px until the row is filled with values, after ...

Annoying Gap Found Between <header> and <nav>

I am encountering an issue with the spacing between the <header> and <nav> in my HTML5 code. Despite trying to adjust the padding, there remains approximately 5 pixels of empty space that I cannot seem to remove. If anyone could provide insigh ...

strategies for aligning content in the center / inquiry

Currently, I am facing a design challenge involving the alignment of a blue div within a green div for aesthetic purposes. After centering the blue div inside the green one using "margin: 10px auto," I encountered an issue with left justifying the text wit ...

When the webpage is displayed from the server, the width of the HTML page appears

When viewing an html page, $(window).width() is displaying different values when hosted on a server compared to locally. Even though my laptop's resolution is 1920 X 1080, the width shows as 1920 when opened in Firefox and Chrome locally, but only as ...

When you hover, there is no writing cursor in sight

I'm looking for a way to display a label on an input field and have a writing cursor show up when hovering over the label. I am not interested in using a placeholder label. Do you have any simple solutions for this? See the code snippet below: JSFiddl ...

creating a form layout with inline buttons

I have encountered an issue with aligning 2 buttons and a form with input type in a single line. Even though I have tried different approaches, I am unable to achieve the desired inline layout. Here is my current setup: .btn-registerLayout { backgr ...

Struggling with Bootstrap 4 Navbar Toggle? It seems to be malfunctioning and not displaying any navigation links

There seems to be an issue with the functionality of the toggle in mobile mode. Although there is some movement, no links are being revealed. You can view the test site here: Here is the codepen link as well: https://codepen.io/boris-k/pen/vYJjqGo Below ...

Distinguishing appearances among various web browsers

How come the menus look different in Firefox compared to Chrome, Safari, and IE? I've tried adjusting the CSS but can't seem to get it just right. Any suggestions on how to fix this? In Firefox, there's an overlapping part at the bottom of ...

CSS Hue Rotate is causing the image to appear darker

The CSS filter hue-rotate seems to be darkening my image according to my observations. For an example, visit: https://jsfiddle.net/m4xy3zrn/ Comparing images with and without the filter applied, it’s clear that the filtered one appears much darker than ...

Boosting Your Theme - Eliminating Redundant Styles

Currently, I am facing more of a best practice issue rather than a coding one. I am in the process of creating a custom bootstrap theme inspired by https://github.com/HackerThemes/theme-kit. Although I have a functional theme that I am satisfied with, I am ...

Using Vue3 to conditionally display a child div based on the class of its parent div

Just starting out with Vue, I'm currently experimenting with the active classes feature from this Vue3 carousel plugin. My goal is to only show the text and link divs for the carousel__slide--active class, but at the moment, all carousel__items are di ...

Disregard a specific CSS class that is assigned to a parent table element

<table class="table table-bordered table-hover table-condensed data_table"> <tbody data-bind="foreach: outboundFaxLogs"> <tr> </tr> <tr> <td></td> <td colsp ...

Border-Encased Navigation Menus in Bootstrap 4

I am a beginner with Bootstrap 4 and I'm curious to know if there is a way in Bootstrap 4 to create navbar menus surrounded by borders similar to the design shown in this image. Thank you in advance! ...

Incorporating CSS into React.js applications

I am currently working on a project using MERN.io. In my project, I am utilizing the React.js component Dropdown. However, the Dropdown component does not come with its own style and CSS, resulting in no styling at all. ... import Dropdown from 'rea ...

Enhance the visual appeal of incoming data using Angular Material's dynamic styling feature

Is it possible to enhance the text with some CSS styling to make each item stand out like in this example: https://i.stack.imgur.com/kSyZE.png I prefer not to include a cross button or provide users with the option to add tags. The data is coming from a R ...

Adjust the margin/padding of the Glyphicon within a Bootstrap badge

Currently, I have a glyphicon inside a badge and I want the glyphicon to have a smaller font size than the text. While I've achieved this, the issue now is that the glyphicon is not vertically centered within the badge. Whenever I attempt to add marg ...

Activating a certain class to prompt a drop-down action

My PHP code is displaying data from my database, but there's a bug where both dropdown menus appear when I click the gear icon. I want only one dropdown to appear when clicking the gear of a specific project. Can you help me fix this issue? It's ...