32

How can I center horizontally and vertically a text? I don't want to use position absolute because I try with it and my other div getting worse. Is there another way to do that ?

div {
    height: 400px;
    width: 800px;
    background: red;
}
<div>
    <h1>This is title</h1>
</div>
    
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Dina
  • 323
  • 1
  • 3
  • 5
  • Do you want the `h1` centered within the `div` or the `div` centered within the viewport/screen? Please clarify, – Marc Audet Jan 03 '16 at 19:23

4 Answers4

20

you can use display flex it enables a flex context for all its direct children, and with flex direction establishes the main-axis, thus defining the direction flex items are placed in the flex container

div{
  height: 400px;
  width: 800px;
  background: red;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}
elreeda
  • 4,525
  • 2
  • 18
  • 45
5

Just do this, which works on every browser:

div{
     height: 400px;
     width: 800px;
     background: red;
     line-height: 400px;
     text-align: center;
}

The line-height property specifies the line height (which centres it vertically), and the text-align:center place it directly in the centre horizontally.

Mmm Donuts
  • 9,551
  • 6
  • 27
  • 49
  • it work also for divs ? because i put this in my website it didnt work – Dina Jan 03 '16 at 19:33
  • 2
    @Dina divs are block elements, so no. If you want it to work on a div, set the div style to `display: inline`. You should use `span` for inline text. – Mmm Donuts Jan 03 '16 at 19:36
1
<div>
  <style>
div {
  position: fixed;
  top: 50%;
  left: 50%;
}</style>
<h1>This is title</h1>
</div>

With position: fixed you set the position to a fixed value, and with top and left both set to 50% you'll get it in the middle of the screen.

Good luck coding!

Here is some more information: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

-1

.container {
    display: table;
}
.centered {
    display: table-cell;
      height: 400px;
      width: 800px;
      background: red;
    text-align: center;
    vertical-align: middle;
    }
<div class="container">
<div class="centered">
  <h1>This is title</h1>
</div>
</div>
Steve Harris
  • 5,014
  • 1
  • 10
  • 25