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>
Best Answer
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;}
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.
<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/
.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>