- vertical-align
- Синтаксис
- Значения
- Объектная модель
- Браузеры
- CSS Vertical Align – How to Center a Div, Text, or an Image [Example Code]
- Why is Centering CSS Elements So Hard?
- How to Center an Element with the CSS Position Property
- How to center text with CSS positioning
- How to center an image with CSS positioning
- How to Center an Element with Flexbox in CSS
- How to center text with Flexbox
- How to center an image with Flexbox
- How to Center an Element with CSS Grid
- How to center text with CSS Grid
- How to center an Image with CSS Grid
- How to Center a Standalone Div, Text, or Image in CSS
- How to center a standalone div in CSS
- How to center standalone text in CSS
- How to center a standalone image in CSS
- Conclusion
- How to Vertically Center Text with CSS
- Use the CSS vertical-align property
- Example of vertically aligning a text:
vertical-align
Выравнивает элемент по вертикали относительно своего родителя, окружающего текста или ячейки таблицы.
Синтаксис
vertical-align: baseline|bottom|middle|sub|super|text-bottom|text-top|top|inherit | значение | проценты
Значения
baseline Выравнивает базовую линию текущего элемента по базовой линии родителя. Если родительский элемент не имеет базовой линии, то за нее принимается нижняя граница элемента. bottom Выравнивает основание текущего элемента по нижней части элемента строки, расположенного ниже всех. middle Выравнивание средней точки элемента по базовой линии родителя плюс половина высоты родительского элемента. sub Элемент изображается как подстрочный, в виде нижнего индекса. Размер шрифта при этом не меняется. super Элемент изображается как надстрочный, в виде верхнего индекса. Размер шрифта остается прежним. text-bottom Нижняя граница элемента выравнивается по самому нижнему краю текущей строки. text-top Верхняя граница элемента выравнивается по самому высокому текстовому элементу текущей строки. top Выравнивание верхнего края элемента по верху самого высокого элемента строки. inherit Наследует значение родителя.
В качестве значения также можно использовать проценты, пикселы или другие доступные единицы. Положительное число смещает элемент вверх относительно базовой линии, в то время как отрицательное число опускает его вниз. При использовании процентов, отсчет ведется от значения свойства line-height , при этом 0% аналогично значению baseline .
Для выравнивания по вертикали в ячейках таблицы применяются следующие значения.
baseline Выравнивает базовую линию ячейки с базовой линией первой текстовой строки или другого вложенного элемента. bottom Выравнивает по нижнему краю ячейки. middle Выравнивает по середине ячейки. top Выравнивает содержимое ячейки по ее верхнему краю.
HTML5 CSS2.1 IE Cr Op Sa Fx
TEX и LATEX
Результат данного примера показан на рис. 1.
Рис. 1. Применение свойства vertical-align
Объектная модель
[window.]document.getElementById(» elementID «).style.verticalAlignБраузеры
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .
CSS Vertical Align – How to Center a Div, Text, or an Image [Example Code]
Kolade Chris
Even with helpful tools like CSS Grid and Flexbox, centering elements in CSS remains notoriously challenging.
It’s been the subject of many jokes and memes, and when you successfully center something, you’ll want to brag about it.
Why is Centering CSS Elements So Hard?
CSS can be tricky to work with. For example, if you’re trying to align something horizontally OR vertically, it’s not that difficult.
You can just set text-align to center for an inline element, and margin: 0 auto would do it for a block-level element.
But issues arise on multiple fronts if you’re trying to combine both vertical and horizontal alignments.
In this tutorial, I will introduce you to three different methods to correctly center a div, text, or image in CSS.
How to Center an Element with the CSS Position Property
The CSS position property takes relative, absolute, fixed, and static (the default) as values. When set, you will be able to apply the top, right, bottom, and left properties to the element.
The combination of relative and absolute values can get a lot of things done, and so you can use it to center anything.
Take a look at the snippets below to see some examples.
How to center text with CSS positioning
I'm a Camper, and I'm vertically centered
* < margin: 0; padding: 0; box-sizing: border-box; >.container < position: relative; height: 400px; border: 2px solid #006100; >.centered-element
How to center an image with CSS positioning
* < margin: 0; padding: 0; box-sizing: border-box; >.container < position: relative; height: 400px; border: 2px solid #006100; >.centered-element
The above code has made the text and image centered vertically. To take care of both vertical and horizontal centering, we need to make a little tweak in the CSS. We’ll set the top property to 50%, and we’ll add a transform on both the X and Y axes.
* < margin: 0; padding: 0; box-sizing: border-box; >.container < position: relative; height: 400px; border: 2px solid #006100; >.centered-element
The text now looks like this:
And the image like this:
Note that I applied the transform property because the child (with the class of centered-element) was slightly off-center. translateY() pushes it to the center vertically and translate on both the X and Y-axis ( translate() ) pushes it to the center vertically and horizontally.
How to Center an Element with Flexbox in CSS
CSS Flexbox handles layouts in one dimension (row or column). With Flexbox, it is pretty easy to center a div, text, or image in just three lines of code.
Check the snippets below for examples.
How to center text with Flexbox
I'm a Camper, and I'm vertically centered
How to center an image with Flexbox
We took care of the vertical alignment in just two lines of code. To make the image and text horizontally centered, add in justify-content: center.
I'm a Camper, I'm now vertically and horizontally centered
The text now looks like this:
And the image like this:
How to Center an Element with CSS Grid
With Flexbox, it is pretty easy to center anything, right? But with CSS Grid, it is really easy to center anything, because two lines of code are enough to do it for you.
How to center text with CSS Grid
I'm a Camper, and I'm vertically centered
How to center an Image with CSS Grid
The above examples takes care of vertical centering for you. To get the text and image centered horizontally too, replace the align items with place items – a combination of both align-items and justify-content :
The text now looks like this:
And the image like this:
How to Center a Standalone Div, Text, or Image in CSS
The three methods above let you center a div, text, or image in a container. You can also center a standalone div, text, or image.
Let’s see how to do that now.
How to center a standalone div in CSS
How to center standalone text in CSS
I'm a Camper, and I'm centered
How to center a standalone image in CSS
img < display: block; margin: 0 auto; >/* Applies a display of block, a margin 0f 0 at the top and bootom, and auto on the left and right */
Conclusion
I hope this tutorial gives you enough knowledge about vertical alignment and how to center elements in CSS so it’s less of a hassle for you in your next project.
Thank you for reading, and keep coding.
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 .
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>