Vertical centering content css

vertical-align

Свойство CSS vertical-align описывает вертикальное позиционирование строчных (inline), строчно-блочных (inline-block) элементов или ячеек таблицы (table-cell).

/* ключевые значения */ 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; /* значения длины () */ vertical-align: 10em; vertical-align: 4px; /* процентные значения () */ vertical-align: 20%; /* глобальные значения */ vertical-align: inherit; vertical-align: initial; vertical-align: unset; 

Свойство vertical-align может использоваться в двух контекстах:

  • Для вертикального позиционирования области строчного элемента внутри области содержащей его строки. Например, с помощью него можно вертикально позиционировать в строке текста:
p> top:img style="vertical-align:top" src="star.png"/> middle:img style="vertical-align:middle" src="star.png"/> bottom:img style="vertical-align:bottom" src="star.png"/> super:img style="vertical-align:super" src="star.png"/> sub:img style="vertical-align:sub" src="star.png"/> p> p> text-top:img style="vertical-align:text-top" src="star.png"/> text-bottom:img style="vertical-align:text-bottom" src="star.png"/> 0.2em:img style="vertical-align:0.2em" src="star.png"/> -1em:img style="vertical-align:-1em" src="star.png"/> 20%:img style="vertical-align:20%" src="star.png"/> -100%:img style="vertical-align:-100%" src="star.png"/> p> 
#*  box-sizing: border-box; > img  margin-right: 0.5em; > p  height: 3em; padding: 0 .5em; font-family: monospace; text-decoration: underline overline; margin-left: auto; margin-right: auto; width: 80%; > 
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>Существует теория, которая утверждает, что если однажды кто-нибудь доподлинно выяснит, что такое и для чего нужна Вселенная, она тотчас же исчезнет, и вместо неё появится нечто ещё более причудливое и необъяснимое.p> p>Существует и другая теория, согласно которой это уже случилось.p> 
table  margin-left: auto; margin-right: auto; width: 80%; > table, th, td  border: 1px solid black; > td  padding: 0.5em; font-family: monospace; > 

Примечание: свойство vertical-align применяется только к строчным элементам и элементам ячеек таблицы: его нельзя использовать для вертикального позиционирования блочных элементов.

Начальное значение baseline
Применяется к строчным элементам и ячейкам таблиц. Это также применяется к ::first-letter и ::first-line .
Наследуется нет
Проценты относятся к line-height самого элемента
Обработка значения для процентов и значений длин, абсолютных длин или ключевых слов, если указаны
Animation type длина

Синтаксис

Свойство vertical-align задаётся одним из ключевых значений, указанных ниже.

Значения для строчных элементов

Значения относительно родительского элемента

Данные значения позиционируют элемент по вертикали относительно родительского элемента:

Выравнивает базовую линию элемента с базовой линией родительского элемента. Базовая линия некоторых замещаемых элементов (en-US) , таких как (en-US), не описана в спецификации HTML, что означает, что их поведение при указании данного ключевого слова может отличаться в зависимости от браузера.

Выравнивает базовую линию элемента с базовой линией подстрочного индекса своего родителя.

Выравнивает базовую линию элемента с базовой линией надстрочного индекса своего родителя.

Выравнивает верхний край элемента с верхним краем шрифта родительского элемента.

Выравнивает нижний край элемента с нижним краем шрифта родительского элемента.

Выравнивает середину элемента с базовой линией своего родителя плюс половина от его высоты (x-height).

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

Поднимает базовую линию элемента на указанную в процентах величину (вычисляется относительно значения свойства line-height ) над базовой линией родительского элемента. Допустимы отрицательные значения.

Значения относительно строки

Следующие значения позиционируют элемент по вертикали относительно всей строки:

Выравнивает верхний край элемента и его потомков с верхним краем всей строки.

Выравнивает нижний край элемента и его потомков с нижним краем всей строки.

Для элементов, у которых нет базовой линии, вместо неё используется нижняя граница внешнего отступа (margin).

Значения для ячеек таблицы

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

Выравнивает базовую линию ячейки с базовой линией всех остальных ячеек этой строки, которые выравнены относительно базовой линии.

Выравнивает верхнюю границу внутреннего отступа (padding) ячейки с верхним краем строки таблицы.

Выравнивает внутреннее поле (padding box) ячейки по центру относительно строки таблицы.

Выравнивает нижнюю границу внутреннего отступа (padding) ячейки с нижним краем строки таблицы.

Допустимы отрицательные значения.

Формальный синтаксис

vertical-align =
[ (en-US) first | (en-US) last ] (en-US) || (en-US)
|| (en-US)

Пример

HTML

div>Изображение img src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по умолчанию.div> div>Изображение img class="top" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по верхнему краю.div> div>Изображение img class="bottom" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по нижнему краю.div> div>Изображение img class="middle" src="frame_image.svg" alt="link" width="32" height="32" /> с выравниванием по центру.div> 

CSS

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

Результат

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 11 февр. 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.

Источник

How TO — Center Elements Vertically

Learn how to center an element vertically and horizontally with CSS.

I am vertically and horizontally centered.

How To Center Anything Vertically

Example

.vertical-center margin: 0;
position: absolute;
top: 50%;
-ms-transform: translateY(-50%);
transform: translateY(-50%);
>

How To Center Vertically AND Horizontally

Example

.center margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
>

I am vertically and horizontally centered.

You can also use flexbox to center things:

Example

.center <
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
>

Tip: Go to our CSS Align Tutorial to learn more about aligning elements.

Tip: Go to our CSS Transform Tutorial to learn more about how to scale elements.

Tip: Go to our CSS Flexbox Tutorial to learn more flexbox.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

CSS Vertical Align – How to Center a Div, Text, or an Image [Example Code]

Kolade Chris

Kolade Chris

CSS Vertical Align – How to Center a Div, Text, or an Image [Example Code]

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

ss1b

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

ss2b

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

ss4b

The text now looks like this:

ss3b

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

ss5b-1

How to center an image with Flexbox

ss6b

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

ss7bb

The text now looks like this:

ss11bb

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

ss8bb

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:

ss7bb-1

ss11bb-1

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

ss12bb

How to center standalone text in CSS

I'm a Camper, and I'm centered

ss13bb

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 */ 

ss14bb

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.

Источник

Читайте также:  Call static var php
Оцените статью