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:
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:
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:
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.
Выравнивание блока div со свойством position:absolute или fixed по центру.
Сегодня урок на тему выравнивания блоков div с помощью технологии CSS по центру.
Здесь есть несколько моментов, которые не совсем просто воспринимаются. На одном из них мне бы хотелось сегодня остановиться.
Когда блоки идут в нормальном потоке, выровнять один, по центру, относительно родительского блока, в котом он находиться, не составляет особого труда.
Для этого используется стандартная CSS конструкция margin:auto.
Но, что делать, если блок, который нужно выровнять по центру имеет абсолютное (absolute) или фиксированное положение (fixed). Такая ситуация иногда бывает.
Т.е. в данном случае наш пример принимает следующий вид.
Есть еще более современное решение этой проблемы — использование flexbox.
position:relative; — у родительского блока было добавлено, чтобы отсчет шел именно с него, а не с тэга <body>
position:absolute; — собственно говоря, само абсолютное позиционирование.
После произведенной манипуляции margin:auto работать уже перестает.
Как быть? Как можно снова выровнять блок по центру?
Сегодня я расскажу о трюке, который используется в этом случае. На самом деле все достаточно просто, нужно только добавить два CSS-свойства для выравниваемого блока.
left:50%; — смещаем блок относительно родительского на 50% влево.
margin-left:-150px; — т.к. отсчет идет с левого верхнего края блока, то для полной ровности, половину блока нужно сместить влево, что мы и делаем отрицательным отступом.
Если ширина блока задается в процентах, то решение может быть следующим:
Если по центру нужно выровнять строку с текстом:
Дело в том, что, когда блоку присваивается свойство с position:absolute. Ширина блока с значением width:auto по умолчанию, становиться равной содержимому. Поэтому свойство text-align не будет работать. Чтобы все начало работать, нужно принудительно увеличить ширину до 100%.
Все, что было сказано выше про position:absolute аналогично можно применить и к блокам, которые имеют position: fixed.
Есть еще более современное решение этой проблемы — использование flexbox.
Абсолютное горизонтальное и вертикальное центрирование
Сколько уже было сломано копий о задачу выравнивания элементов на странице. Предлагаю вашему вниманию перевод отличной статьи с решением этой проблемы от Стефана Шоу (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.
Смещения
Если на сайте присутствует фиксированная шапка или требуется сделать какой-то другой отступ, просто нужно добавить в стили код вроде 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. Главный недостаток — дополнительная разметка: требуется аж три элемента:
- Изменяемая высота
- Верстка не едет при большом количестве текста в блоке
- Кроссбраузерность
- Сложная структура
Flexbox
Будущее CSS, flexbox будет решать множество сегодняшних проблем верстки. Подробно об этом написано в статье Smashing Magazine, которая называется Centering Elements with Flexbox.
How to center a "position: absolute" element
I’m having a problem centering an element that has the attribute position set to absolute . Does anyone know why the images are not centered?
31 Answers 31
If you have set a width you may use:
Without knowing the width / height of the positioned 1 element, it is still possible to align it as follows:
It’s worth noting that CSS Transform is supported in IE9 and above. (Vendor prefixes omitted for brevity)
Explanation
Adding top / left of 50% moves the top/left margin edge of the element to the middle of the parent, and translate() function with the (negative) value of -50% moves the element by the half of its size. Hence the element will be positioned at the middle.
This is because a percentage value on top / left properties is relative to the height/width of the parent element (which is creating a containing block).
While a percentage value on translate() transform function is relative to width/height of the element itself (Actually it refers to the size of bounding box).
For unidirectional alignment, go with translateX(-50%) or translateY(-50%) instead.
1. An element with a position other than static . I.e. relative , absolute , fixed values.
Centering something absolute ly positioned is rather convoluted in CSS.
Change margin-left to (negative) half the width of the element you are trying to center.
Div vertically and horizontally aligned center
Note : Elements should have width and height to be set
If you want to center an absolute element
If you want a container to be centered left to right, but not with top to bottom
If you want a container to be centered top to bottom, regardless of being left to right
Update as of December 15, 2015
Well I learnt this another new trick few months ago. Assuming that you have a relative parent element.
Here goes your absolute element.
With this, I think it’s a better answer than my old solution. Since you don’t have to specify width AND height. This one it adapts the content of the element itself.
Update as of April 23, 2021
It does not answer to OP’s question about position absolute, but if you want alternative solution, there’s this called flexbox . Here’s an example.
What it does is the container is converted to flex and to align child items to center on horizontal is by using justify-content:center and vertical is to use align-items:center . It does support modern browsers too, so it’s safe to use.