Html по центру страницы по вертикали

How to Vertically Center Text with CSS

Centering elements vertically with CSS often gives trouble. However, there are several ways of vertical centering, and each is easy to use.

Use the CSS vertical-align property

The vertical-align property is used to vertically center inline elements.

The values of the vertical-align property align the element relative to its parent element:

  • Line-relative values vertically align an element relative to the entire line.
  • Values for table cells are relative to the table-height-algorithm, which commonly refers to the height of the row.

It is important to note that it is possible to nudge text vertically up or down in CSS using the vertical-align property. This property sets the vertical alignment of an inline or table-cell element, and can be used to adjust the vertical position of text within its container.

Note that vertical-align only applies to inline or table-cell elements, so it may not work as expected on block-level elements such as or

. In such cases, you may need to wrap the text in an inline or table-cell element to apply vertical-align .

Читайте также:  Html input center value

Example of vertically aligning a text:

html> html> head> title>Title of the document title> style> div < display: table-cell; width: 250px; height: 200px; padding: 10px; border: 3px dashed #1c87c9; vertical-align: middle; > style> head> body> div>Vertically aligned text div> body> html>

Источник

HTML/CSS: как центрировать по вертикали

HTML/CSS: как центрировать по вертикали главное изображение

При изучении стилизации HTML-страниц и механизмов выравнивания элементов средствами CSS, начинающий разработчик, как правило, сначала знакомится со способами горизонтального выравнивания элементов. В их числе, например, text-align: center; и margin: 0 auto; . С выравниванием по вертикали возникает больше вопросов. В этой статье разберем пять способов выравнивания элементов в HTML и CSS по вертикали.

У каждого описанного способа есть свои преимущества и недостатки, поэтому подходить к их использованию стоит критически. В определенной ситуации один способ может подходить идеально, а другой — оказаться совершенно бесполезным.

1. У правила для горизонтального выравнивания текста text-align: center; , которое уже упоминалось выше, есть собрат, который называется vertical-align . Как и text-align , vertical-align выравнивает элементы со строчным или строчно-блочным типом бокса. Отличие в том, что свойство text-align применяется к родительскому блоку, а vertical-align необходимо применять непосредственно к выравниваемому элементу.

Свойство vertical-align удобно применять, когда необходимо, например, выровнять иконку внутри строки или два рядом стоящих строчно-блочных элемента. Важно понимать, что vertical-align выравнивает элемент относительно содержащей строки, а не относительно ближайших элементов.

Кроме того, свойство vertical-align можно использовать для того, чтобы выравнивать контент в ячейке таблицы.

2. Для тех, кто не знаком с принципами работы интерлиньяжа и свойством line-height , может стать откровением, что текст располагается посередине содержащей его строки. Этим можно пользоваться при выравнивании. Предположим, что у вас есть элементарный footer, в котором нужно расположить по центру копирайт:

  

Copyright - ThriveTalk 2017

Допустим, что высота футера равна 80px. Для того, чтобы текст вертикально встал ровно по центру, достаточно написать в CSS следующее:

У этого способа есть недостаток. Его удобно применять, когда вы уверены, что выравниваемый элемент не будет переполняться. В противном случае при переносе строки между текстом появятся большие вертикальные отступы, что почти наверняка станет нежелаемым поведением.

3. Для предотвращения нежелаемного поведения, описанного в примере выше, можно использовать метод выравнивания: padding . Значения padding-top и padding-bottom помогут вам не только центрировать по вертикали, но и застраховаться от переполнения. Рассмотрим пример:

Предположим, вы верстаете кнопку, при нажатии на которую происходит переход на страницу заказа товара. Высота кнопки не должна превышать 50px. Из макета вы выгрузили следующие стили:

Высота контента внутри кнопки равна высоте строки и составляет 20px. Чтобы текст кнопки встал по центру, необходимо распределить по свойствам padding-top и padding-bottom оставшееся пространство следующим образом: (50px — 20px) / 2.

В результате получаем следующее:

Если текст кнопки измениться с «Заказать» на «Заказать товар онлайн» и перестанет помещаться на одной строке, кнопка сохранит нужный вид, а текст внутри неё по-прежнему будет находиться по центру.

Выравнивание при помощи padding универсально и подходит как для фразовых элементов, так и для выравнивания элементов с блочным типом бокса (но только в некоторых случаях).

4. Еще один инструмент — Flexbox. Внутри flex-контейнера любой элемент, будь то блочный, строчный или даже псевдоэлемент, становится flex-элементом, с которым можно производить любые манипуляции. В этой статье мы не будем подробно останавливаться на flex-свойств, почитать о них можно, например, тут.

У Flexbox есть ряд преимуществ перед обыкновенным выравниванием — в первую очередь это создание крупных сеточных структур и макросеток.

5. А что, если элемент абсолютно спозиционирован? Предположим, что вы сверстали модальное окно, которое нужно спозиционировать не относительно другого элемента, а относительно окна браузера. В этом случае можно использовать position: fixed; .

Стоит отметить, что все описываемые далее действия применимы и в случаях, когда нужно выполнить абсолютное позиционирование внутри другого элемента.

Положением спозиционированных элементов управляют свойства top , right , bottom , left . Попробуем следующее:

В данном случае модальное окно расположено не верно: ровно по центру находится левый верхний угол модального окна, а не его физический центр. Для того, чтобы выполнить его абсолютное позиционирование, изменим положение модального окна с помощью отрицательного margin :

У применения свойства margin в этой ситуации существует один недостаток. При изменении свойств width и/или height модального окна вам придется вручную «подкручивать» значения отрицательного margin , чтобы добиться половины размера его ширины и высоты. Этого можно избежать, используя вместо margin свойство transform . А transform: translate(X, Y) позволяет регулировать смещение элемента относительно исходного положение. Например, так:

В отличие от свойства margin , значения которого вычисляются от ширины родительского элемента, transform: translate(X, Y) берет за основу габариты самого элемента — в данном случае, модального окна. А это то, что нам и нужно. В результате, модальное окно будет всегда находиться в центре. Независимо от своих размеров.

Источник

vertical-align

The vertical-align CSS property sets vertical alignment of an inline, inline-block or table-cell box.

Try it

The vertical-align property can be used in two contexts:

  • To vertically align an inline-level element’s box inside its containing line box. For example, it could be used to vertically position an image in a line of text.
  • To vertically align the content of a cell in a table.

Note that vertical-align only applies to inline, inline-block and table-cell elements: you can’t use it to vertically align block-level elements.

Syntax

/* Keyword values */ vertical-align: baseline; vertical-align: sub; vertical-align: super; vertical-align: text-top; vertical-align: text-bottom; vertical-align: middle; vertical-align: top; vertical-align: bottom; /* values */ vertical-align: 10em; vertical-align: 4px; /* values */ vertical-align: 20%; /* Global values */ vertical-align: inherit; vertical-align: initial; vertical-align: revert; vertical-align: revert-layer; vertical-align: unset; 

The vertical-align property is specified as one of the values listed below.

Values for inline elements

Parent-relative values

These values vertically align the element relative to its parent element:

Aligns the baseline of the element with the subscript-baseline of its parent.

Aligns the baseline of the element with the superscript-baseline of its parent.

Aligns the top of the element with the top of the parent element’s font.

Aligns the bottom of the element with the bottom of the parent element’s font.

Aligns the middle of the element with the baseline plus half the x-height of the parent.

Aligns the baseline of the element to the given length above the baseline of its parent. A negative value is allowed.

Aligns the baseline of the element to the given percentage above the baseline of its parent, with the value being a percentage of the line-height property. A negative value is allowed.

Line-relative values

The following values vertically align the element relative to the entire line:

Aligns the top of the element and its descendants with the top of the entire line.

Aligns the bottom of the element and its descendants with the bottom of the entire line.

For elements that do not have a baseline, the bottom margin edge is used instead.

Values for table cells

baseline (and sub , super , text-top , text-bottom , , and )

Aligns the baseline of the cell with the baseline of all other cells in the row that are baseline-aligned.

Aligns the top padding edge of the cell with the top of the row.

Centers the padding box of the cell within the row.

Aligns the bottom padding edge of the cell with the bottom of the row.

Negative values are allowed.

Formal definition

Initial value baseline
Applies to inline-level and table-cell elements. It also applies to ::first-letter and ::first-line .
Inherited no
Percentages refer to the line-height of the element itself
Computed value for percentage and length values, the absolute length, otherwise the keyword as specified
Animation type a length

Formal syntax

Examples

Basic example

HTML

div> An img src="frame_image.svg" alt="link" width="32" height="32" /> image with a default alignment. div> div> An img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-top alignment. div> div> An img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> image with a text-bottom alignment. div> div> An img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> image with a middle alignment. div> 

CSS

img.top  vertical-align: text-top; > img.bottom  vertical-align: text-bottom; > img.middle  vertical-align: middle; > 

Result

Vertical alignment in a line box

HTML

p> top: img style="vertical-align: top" src="star.png" alt="star"/> middle: img style="vertical-align: middle" src="star.png" alt="star"/> bottom: img style="vertical-align: bottom" src="star.png" alt="star"/> super: img style="vertical-align: super" src="star.png" alt="star"/> sub: img style="vertical-align: sub" src="star.png" alt="star"/> p> p> text-top: img style="vertical-align: text-top" src="star.png" alt="star"/> text-bottom: img style="vertical-align: text-bottom" src="star.png" alt="star"/> 0.2em: img style="vertical-align: 0.2em" src="star.png" alt="star"/> -1em: img style="vertical-align: -1em" src="star.png" alt="star"/> 20%: img style="vertical-align: 20%" src="star.png" alt="star"/> -100%: img style="vertical-align: -100%" src="star.png" alt="star"/> p> 
#*  box-sizing: border-box; > img  margin-right: 0.5em; > p  height: 3em; padding: 0 0.5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; > 

Result

Vertical alignment in a table cell

HTML

table> tr> td style="vertical-align: baseline">baselinetd> td style="vertical-align: top">toptd> td style="vertical-align: middle">middletd> td style="vertical-align: bottom">bottomtd> td> p> There is a theory which states that if ever anyone discovers exactly what the Universe is for and why it is here, it will instantly disappear and be replaced by something even more bizarre and inexplicable. p> p> There is another theory which states that this has already happened. p> td> tr> table> 

CSS

table  margin-left: auto; margin-right: auto; width: 80%; > table, th, td  border: 1px solid black; > td  padding: 0.5em; font-family: monospace; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью