-2

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
dyari
  • 19
  • 4
  • 3
    The problem is we have so little to go off here - we don't know what anything looks like and what result you want. Or what you mean with `your div of choosing' - it needs to be centered on _something_. Flexboxes to the rescue here, you can do exactly what you want with very few downsides, but it needs some tweaking on the side for it to work as you want it to. – somethinghere Mar 14 '23 at 14:49
  • the only thing i can think of without removing the `center` tags is using `text-align` – 120 099 101 105 110 103 Mar 14 '23 at 14:53
  • 1
    @120099101105110103 no please don't use text-align to aling divs..... in the 2023 exists flexbox and grid – Sfili_81 Mar 14 '23 at 14:57
  • Does this answer your question? [How to center a button within a div?](https://stackoverflow.com/questions/7560832/how-to-center-a-button-within-a-div) – benicamera Mar 14 '23 at 15:02
  • 4
    2023 and we are still asking about how to center .. and still answering such a question – Temani Afif Mar 14 '23 at 15:03
  • @TemaniAfif The confusion starts when its 2023 and after all the research I did on internet still I couldn't find the right simple answer for how to center a div you all gotta check yourselves first then decide to comment.... – dyari Mar 14 '23 at 15:08
  • @Sfili_81 something like this? https://codepen.io/120099101105110103/pen/WNgzKxY – 120 099 101 105 110 103 Mar 14 '23 at 15:08
  • @dyari your question is a duplicate, you can see there are many answers on how to center elements – Sfili_81 Mar 14 '23 at 15:18
  • 1
    @dyari this is worth a look too http://howtocenterincss.com – Adam Mar 14 '23 at 15:37
  • @dyari put your title on google and you have a whole week (if not month) of reading resources – Temani Afif Mar 14 '23 at 15:51

2 Answers2

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>
Adam
  • 5,495
  • 2
  • 7
  • 24
Moussa Bistami
  • 929
  • 5
  • 15
-1

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>
wbohrer28
  • 1
  • 4