dyari
dyari

Reputation: 65

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.

Upvotes: 1

Views: 46894

Answers (2)

Moussa Bistami
Moussa Bistami

Reputation: 1097

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>

Upvotes: 15

wbohrer28
wbohrer28

Reputation: 31

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>

Upvotes: 2

Related Questions