-2

Can I calculate with width of <h1> (depends on text) and center this <h1> horizontally in <body>?

Thanks for any help and hint!

dippas
  • 58,591
  • 15
  • 114
  • 126
John Doe
  • 3
  • 6
  • 1
    your question isn't very clear - but to center a block-level element like `h1` the usual method is to set its `margin-left` and `margin-right` to `auto` – Robin Zigmond May 18 '19 at 21:12
  • Can u post some example please? I tried it, but the

    did not move. `position: absolute; top: 20px; margin-left: auto; margin-right: auto;`

    – John Doe May 18 '19 at 21:17
  • 1
    it would be better if you post some code so we can help you better, anyway h1 is a block element so it will take full line width, so in order to position it on the middle, you must decrease its width and then use margin:auto, for example width:50%; then margin:auto; – MAHFOUDH KERBOUCHE May 18 '19 at 21:22
  • If you are using `position: absolute;`, you should use `left: 50%;` and then `transform: translate(-50%)`. – Ian Holden May 18 '19 at 21:25

1 Answers1

0

Robin Zigmond is correct in their comment. You can center a block-level element by setting it's margin-left and margin-right to auto. It will appear centered if it's width is not 100% of it's parent container:

h1 {
    margin-left: auto;
    margin-right: auto;
}

If its width is 100% of its parent container, you could use text-align to set the text to center:

h1 {
    text-align: center;
}
Ian Holden
  • 331
  • 1
  • 2
  • 11