- How to center an absolute positioned item vertically?
- 5 Answers 5
- 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
- How to center div vertically inside of absolutely positioned parent div
- 11 Answers 11
- 1. Using transform and top
- 2. Using inline-block (pseudo-)elements
- Абсолютное горизонтальное и вертикальное центрирование
- Достоинства
- Недостатки
- Совместимость с браузерами
- Внутри контейнера
- С использованием viewport
- Адаптивность
- Смещения
- Много контента
- Изображения
- Изменяемая высота
- Другие способы
- Отрицательный margin
- Использование transform
- Table-cell
- Flexbox
- Итог
How to center an absolute positioned item vertically?
top:50% sets the top edge of the element to be 50% down from the top of its first non-statically positioned parent.
5 Answers 5
To center something vertically, you need do add a top: 50% and a negative margin-top: -(elementHeight/2) .
You can also do it this way:
Big advantage, no math required.
However, this works because you specified width and height. This gets trickier when you use percentages.
Note: I made the blocks half the size so they fit in the fiddle window. will also work with the larger blocks.
Works Well With Replaced Elements
This technique does a pretty good job if you are positioning an image, which has specific dimensions (though you may not know them).
This is actually out of the CSS 2.1 spec, so it could work as far back as IE6, but I have not tried it.
Vertical alignment is based off of other inline elements. The best way I’ve found to vertically align something is to add a psuedo class.
It’s easy to vertically align something if you know the dimensions, like some of the other answers have noted. It makes it harder though, when you don’t have specific dimensions and needs to be more free.
Basically, the method aligns the psuedo class with the rest of the content to align middle whatever is inside the container.
div#container < width: 600px; height: 600px; text-align:center; >div#container:before < content:''; height:100%; display:inline-block; vertical-align:middle; >div#cen
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.
How to center div vertically inside of absolutely positioned parent div
I am trying to get blue container in the middle of pink one, however seems vertical-align: middle; doesn’t do the job in that case.
Result: Expectation:
Please suggest how can I achieve that. Jsfiddle
@Vucko yes — that is prerequisite as this is just simplified version of very complex layout, but absolute position in both top divs is key thing.
@Vladimirs I can only think of margin-top: calc((56px — 16px) / 2) , where 56px — parent height , 16px — element height/font-size — JSFiddle
11 Answers 11
First of all note that vertical-align is only applicable to table cells and inline-level elements.
There are couple of ways to achieve vertical alignments which may or may not meet your needs. However I’ll show you two methods from my favorites:
1. Using transform and top
The key point is that a percentage value on top is relative to the height of the containing block; While a percentage value on transform s is relative to the size of the box itself (the bounding box).
If you experience font rendering issues (blurry font), the fix is to add perspective(1px) to the transform declaration so it becomes:
transform: perspective(1px) translateY(-50%);
It’s worth noting that CSS transform is supported in IE9+.
2. Using inline-block (pseudo-)elements
In this method, we have two sibling inline-block elements which are aligned vertically at the middle by vertical-align: middle declaration.
One of them has a height of 100% of its parent and the other is our desired element whose we wanted to align it at the middle.
.parent < text-align: left; position: absolute; height: 56px; background-color: pink; white-space: nowrap; font-size: 0; /* remove the gap between inline level elements */ >.dummy-child < height: 100%; >.valign < font-size: 16px; /* re-set the font-size */ >.dummy-child, .valign
Абсолютное горизонтальное и вертикальное центрирование
Сколько уже было сломано копий о задачу выравнивания элементов на странице. Предлагаю вашему вниманию перевод отличной статьи с решением этой проблемы от Стефана Шоу (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
- Требует множество разнообразных префиксов для корректной работы в современных браузерах
- Возможные проблемы производительности
Итог
Каждый способ имеет преимущества и недостатки. По сути, выбор сводится к выбору браузеров, которые должны поддерживаться