M
M
Mikhail Faito2012-04-18 14:14:03
css
Mikhail Faito, 2012-04-18 14:14:03

Placing text in the center of the screen

Friends, tell me the most cross-browser solution for placing text on the page in the center of the browser window (just in case, I’ll explain: this is when the indents from the top, bottom, left and right of the window borders to the text are the same in pairs). Thanks in advance!

Answer the question

In order to leave comments, you need to log in

7 answer(s)
K
kyrie, 2012-04-18
@kyrie

In the general case, there is no solution, but there are a lot of particulars.
If the text is in one line and it is possible to use an absolute (which is far from always) then -
position:absolute;
width:100%;
top:50%;
text-align:center;
If the height of the block is known and you can use the absolute, then the option proposed above.
If you cannot use the absolute, but the height of the block and the text in one line are known, then through the line-height equal to the height of the block.
Well, and a 100% cross-browser classic that everyone always forgets about - to make a table with one cell.

R
Ruslan Banochkin, 2015-09-04
@Sk8er

A bunch of options above with a lot of code, but you can do everything with just a couple of lines in CSS using Flexbox. So, for example: blog.sk8er.name/rabota/vyravnivanie-bloka-po-centru

S
ssbxlan, 2012-04-18
@ssbxlan

#center {
  top: 50%; /* Отступ в процентах от верхнего края окна */
  left: 50%; /* Отступ в процентах от левого края окна */
  width: 450px; /* Ширина блока */
  height: 450px; /* Высота блока */
  position: absolute; /* Абсолютное позиционирование блока */
  margin-top: -225px; /* Отрицательный отступ от верхнего края страницы, должен равняться половине высоты блока со знаком минус */
  margin-left: -225px; /* Отрицательный отступ от левого края страницы, должен равняться половине высоты блока со знаком минус */
}
The first result is googled this option, I always used it

S
Softlink, 2012-04-18
@Softlink

td {
text-align: center;
vertical-align: middle;
}

A
alexandy, 2012-04-18
@aleksandy

<html>
    <head>
        <style type="text/css">
            html, body {
                height : 100%;
                width : 100%;
                overflow : hidden;
            }
            .wrapper {
                height : 100%;
                width : 100%;
                padding: 20px;
            }
            .content {
                height : 100%;
                width : 100%;
            }
        </style>
    </head>
    <body>
        <div class="wrapper">
            <div class="content">Content here</div>
        </div>
    </body>
</html>

Z
Zakonoposlushniy, 2017-03-06
@Zakonoposlushniy

Thanks for the options.

V
vasea_sd, 2020-02-21
@vasea_sd

How is this code worse than
Position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question