- How to Center an Absolutely Positioned Element in a Div
- Create HTML
- Add CSS
- Example of centering an absolutely positioned element with unknown dimensions:
- Result
- Example of centering an absolutely positioned element with fixed dimensions:
- How to Center an Absolute Positioned Element Vertically and Horizontally with CSS
- Code Example
- How does the absolute position work?
- How to position absolute elements in the center
- Wrapping up
- Абсолютное горизонтальное и вертикальное центрирование
- Достоинства
- Недостатки
- Совместимость с браузерами
- Внутри контейнера
- С использованием viewport
- Адаптивность
- Смещения
- Много контента
- Изображения
- Изменяемая высота
- Другие способы
- Отрицательный margin
- Использование transform
- Table-cell
- Flexbox
- Итог
How to Center an Absolutely Positioned Element in a Div
In CSS, centering an absolutely positioned element can cause some difficulties. It can be especially complicated if the width of the element is unknown.
Below, we’ll discuss two cases when we know the width, and the width is unknown.
First, we will center an absolutely positioned element, the dimensions of which are unknown.
Create HTML
body> div class="outer"> div class="inner"> A centered text. br/>The length of the text, height or width does not matter. div> div> body>
Add CSS
Set the position to «relative» for the «outer» class and «absolute» for the «inner» one.
.outer < position: relative; margin: 5%; width: 80%; height: 500px; border: 2px solid #1703fc; > .inner < position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); max-width: 50%; text-align: center; border: 2px solid #468a4d; >
Example of centering an absolutely positioned element with unknown dimensions:
html> html> head> title>Title of the document title> style> .outer < position: relative; margin: 5%; width: 80%; height: 500px; border: 2px solid #1703fc; > .inner < position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); max-width: 50%; text-align: center; border: 2px solid #468a4d; > style> head> body> div class="outer"> div class="inner">A centered text. br/>The length of the text, height or width does not matter. div> div> body> html>
Result
In the example above, the left property is relative to the parent element, while the transform is relative to its parent’s width/height. Thus, you can have a centered element with a flexible width on both the child and parent elements.
Next, we’ll show an example of centering an absolutely positioned element, which has exact dimensions. Here, the inner box will remain centered regardless of the width of the outer element.
Example of centering an absolutely positioned element with fixed dimensions:
html> html> head> title>Title of the document title> style> .outer < position: relative; width: 40%; height: 120px; margin: 20px auto; border: 2px solid #468a4d; > .inner < position: absolute; width: 100px; height: 100px; top: 10px; left: 50%; margin-left: -50px; background-color: #1703fc; > style> head> body> div class="outer"> div class="inner"> div> div> body> html>
How to Center an Absolute Positioned Element Vertically and Horizontally with CSS
Dillion Megida
Absolute positioned elements are removed from the flow of a document. And sometimes, knowing how to correctly position such elements in the center of the page can be confusing.
I mean, CSS is confusing already. 😅
In this article, I will show you how to center an absolute element either vertically or horizontally – or both – in a container.
Code Example
To center an elemenet horizontally:
To center an element vertically:
To center an element both vertically and horizontally:
position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto;
But if you would like to understand how I came to these solutions, read further for more explanation.
How does the absolute position work?
By default, elements have a static position unless specified otherwise as absolute , fixed , relative or sticky . You can read this article on CSS position styles to understand the difference.
I will use the following UI to explain how absolute elements work:
Here is the code for the UI:
.container < margin: 20px; display: flex; border: 1px solid black; padding: 20px; width: 400px; >.blue-block, .green-block, .black-block < width: 100px; height: 100px; >.blue-block < background-color: blue; >.green-block < background-color: green; >.black-block
This container has three blocks: blue, green, and black, respectively. All blocks are currently static , so they are ordered the same way in the DOM, just as they are in the code.
What happens when you give the green block an absolute position:
You can see now that the green block has left the document flow. The container only applies the flex display to the blue and black elements, and the green element wanders around without affecting the others.
So, what if we wanted to position this green block at the center of the container?
How to position absolute elements in the center
Positioning static elements to the center usually involve auto margins, so a margin: auto should suffice, right?
It definitely does not. As an absolute element, it loses its flow in the container. Maybe a left: auto and right: auto then:
Still nothing. At this point, you may be tempted to use hardcoded values:
.blue-block, .black-block < display: none; >.green-block
This result looks perfect (or almost) but is not the best solution because when you change the size of the container, you have to change the hardcoded values.
Now, let’s look at how you can center absolute positioned elements.
The first part is applying a relative position to the container:
Applying a relative position to the container gives the absolute element a boundary. Absolute elements are bounded by the closest relative positioned parent. But if none of that exists, they will be bounded by the viewport.
Next, we will center the block horizontally. Apply a left and right property with the value of 0. These properties respectively specify the distance of the left edge (of the block) to the container and the right edge to the container.
The left takes more precendence because the container displays elements from left to right.
The beauty comes in with the next style:
And you have a horizontally centered absolute element. Think of the left and right properties specifying an inner container for the block. Within this container, the left and right margins can be auto so that they are equal and bring the element to the center.
To center this block vertically, you can already guess that it goes this way:
The top and bottom specify the distance between the top and bottom edges of the block, which looks like an inner container. Using auto creates equal margins for margin-top and margin-bottom .
Bringing the two concepts together, you can horizontally and vertically center the block like this:
With this approach, the element stays at the center if you resize the container.
Wrapping up
Absolute elements behave differently than static elements – they leave the document flow and, by default, do not respect the container they were declared in.
With a relative positioned parent element, an absolute positioned element has a boundary. And with the left , right , top and bottom properties with a value of 0 (specifying the distance of the edges), and an auto margin, the absolute element is centered in the parent element.
Note that this is not the only way to position absolute elements in the center. I have seen someone online use a transform: translate. to achieve this, too. You can look into that if you like.
Абсолютное горизонтальное и вертикальное центрирование
Сколько уже было сломано копий о задачу выравнивания элементов на странице. Предлагаю вашему вниманию перевод отличной статьи с решением этой проблемы от Стефана Шоу (Stephen Shaw) для Smashing Magazine — Absolute Horizontal And Vertical Centering In CSS.
Все мы знали о margin: 0 auto; для горизонтального центрирования, но margin: auto; не работало для вертикального. Это можно легко исправить, просто задав высоту и применив следующие стили:
Я не первый, кто предложил это решение, однако такой подход редко применяется при вертикальном выравнивании. В комментариях к статье How to Center Anything With CSS Simon ссылается на пример jsFiddle, где приводится отличное решение для вертикального центрирования. Вот еще несколько источников на эту тему.
Рассмотрим способ поближе.
Достоинства
- Кроссбраузерность (включая IE 8-10)
- Никакой дополнительной разметки, минимум стилей
- Адаптивность
- Независимость от padding (без box-sizing!)
- Работает для изображений
Недостатки
- Должна быть задана высота (см. Variable Height)
- Рекомендуется задать overflow: auto, чтобы контент не расползался
- Не работает на Windows Phone
Совместимость с браузерами
Метод был протестирован, и прекрасно работает в Chrome, Firefox, Safari, Mobile Safari и даже IE 8-10. Один пользователь упоминал, что контент не выравнивается по вертикали на Windows Phone.
Внутри контейнера
Контент, размещенный в контейнер с position: relative будет прекрасно выравниваться:
С использованием viewport
Установим для контента position: fixed и зададим z-index:
Адаптивность
Главное преимущество описываемого способа — это прекрасная работа, когда высота или ширина задана в процентах, да еще и понимание min-width/max-width и min-height/max-height.
.Absolute-Center.is-Responsive
Смещения
Если на сайте присутствует фиксированная шапка или требуется сделать какой-то другой отступ, просто нужно добавить в стили код вроде top: 70px; Пока задан margin: auto; блок с контентом будет корректно центрироваться по высоте.
Еще можно выравнивать контент по нужной стороне, оставляя центрирование по высоте. Для этого нужно использовать right: 0; left: auto; для выравнивания справа или left: 0; right: auto; для выравнивания слева.
Много контента
Для того, чтобы большое количество контента не позволяло верстке разъезжаться, используем overflow: auto. Появится вертикальная прокрутка. Также можно добавить max-height: 100%; если у контента нет дополнительных отступов.
Изображения
Способ отлично работает и для изображений! Добавим стиль height: auto; тогда картинка будет масштабироваться вместе с контейнером.
Изменяемая высота
Описываемый способ требует заданной высоты блока, которая может быть указана в процентах и контролироваться с помощью max-height, что делает метод идеальным для адаптивных сайтов. Один из способов не задавать высоту — использование display: table. При этом блок контента центрируется независимо от размера.
Могут возникнуть проблемы с кроссбраузерностью, возможно следует использовать способ с table-cell (описан ниже).
- Firefox/IE8: использование display: table выравнивает блок вертикально по верхней границе документа.
- IE9/10: использование display: table выравнивает блок по левому верхнему углу страницы.
- Mobile Safari: если ширина задана в процентах, страдает горизонтальное центрирование
Другие способы
Описанный способ отлично работает в большинстве случаев, но есть и другие методы, которые могут быть применимы для решения специфических задач.
Отрицательный margin
Наверное, самый популярный способ. Подходит, если известны размеры блока.
- Не адаптивный
- Ползет верстка, если в контейнере слишком много контента
- Приходится компенсировать отступы или использовать box-sizing: border-box
Использование transform
Один из самых простых способов, поддерживает изменение высоты. Есть подробная статья на эту тему — «Centering Percentage Width/Height Elements» от CSS-Tricks.
- Не работает в IE 8
- Использование префиксов
- Может мешать работе других эффектов с transform
- В некоторых случаях при рендеринге размываются края блока и текст
Table-cell
Возможно один из самых лучших и простых способов. Подробно описан в статье «Flexible height vertical centering with CSS, beyond IE7» от 456bereastreet. Главный недостаток — дополнительная разметка: требуется аж три элемента:
.Pos-Container.is-Table < display: table; >.is-Table .Table-Cell < display: table-cell; vertical-align: middle; >.is-Table .Center-Block
- Изменяемая высота
- Верстка не едет при большом количестве текста в блоке
- Кроссбраузерность
Flexbox
Будущее CSS, flexbox будет решать множество сегодняшних проблем верстки. Подробно об этом написано в статье Smashing Magazine, которая называется Centering Elements with Flexbox.
- Контаент может быть любой высоты или ширины
- Может использоваться в более сложных случаях
- Нет поддержки IE 8-9
- Требуется контейнер или стили в body
- Требует множество разнообразных префиксов для корректной работы в современных браузерах
- Возможные проблемы производительности
Итог
Каждый способ имеет преимущества и недостатки. По сути, выбор сводится к выбору браузеров, которые должны поддерживаться