htmlcssalignmentcenter

How to center a div in HTML


I want to center a div without centering its children like so:

<center>
<div>
<h1>Hello World!</h1>
</div>
</center>

As you can see I only want the div to be centered not the h1 inside the div. I want the text to remain to its place only centering the div, not to mention I saw some resources that adds "display: flex;" and "justify-content: center;" in body but this will center all the divs in the page I want it to be applied in the div I choose.


Solution

  • It would center your element without centring its children

    <div style="display: flex; flex-direction: row; align-items: center; justify-content: center;">
      <div>
        <h1>This is your text</h1>
      </div>
    </div>