skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. You could use display: flex; and justify-content: center; in a div spanning the entire viewport width that contains the div you want to center.

    Example:

    <div style="display: flex; justify-content: center;" width="100%">
      <!-- ↓ The original div -->
      <div>
        <h1>Hello World!</h1>
      </div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search