- Выравниваем блок по центру страницы
- Вариант 1. Отрицательный отступ.
- Вариант 2. Автоматический отступ.
- Вариант 3. Таблица.
- Вариант 4. Псевдо-элемент.
- Вариант 5. Flexbox.
- Вариант 6. Transform.
- Вариант 7. Кнопка.
- Бонус
- 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
Выравниваем блок по центру страницы
Очень часто стоит задача выровнять блок по центру страницы / экрана, да ещё и так, чтобы без ява-скрипта, без задания жёстких размеров или отрицательных отступов, ещё чтобы и скроллбары работали у родителя, если блок превышает его размеры. В сети ходят достаточно много однообразных примеров как выровнять блок по центру экрана. Как правило большинство из них основаны на одних принципах.
Ниже представлены основные способы решения задачи, их плюсы и минусы. Чтобы понимать суть примеров, рекомендую уменьшить высоту / ширину окошка Result в примерах по указанным ссылкам.
Вариант 1. Отрицательный отступ.
Позиционируем блок атрибутами top и left на 50%, и заранее зная высоту и ширину блока, задаём отрицательный margin, который равен половине размера блока. Огромным минусом данного варианта является то, что нужно подсчитывать отрицательные отступы. Так же блок не совсем корректно ведёт себя в окружении скроллбаров — он попросту обрезается так как имеет отрицательные отступы.
Вариант 2. Автоматический отступ.
Менее распространённый, но схожий с первым. Для блока задаём ширину и высоту, позиционируем атрибутами top right bottom left на 0, и задаём margin auto. Плюсом данного варианта являются рабочие скроллбары у родителя, если у последнего задана 100% ширина и высота. Минусом данного способ является жёсткое задание размеров.
Вариант 3. Таблица.
Задаём родителю табличные стили, ячейке родителя устанавливаем выравнивание текста по центру. А блоку задаём модель строчного блока. Минусами мы получаем не рабочие скроллбары, и в целом не эстетичность «эмуляции» таблицы.
Чтобы добавить скролл в данный пример, придётся добавить в конструкцию ещё один элемент.
Пример: jsfiddle.net/serdidg/xkb615mu.
Вариант 4. Псевдо-элемент.
Данный вариант лишён всех проблем, перечисленных у предыдущих способов, а так же решает первоначально поставленные задачи. Суть состоит в том, чтобы у родителя задать стили псевдо-элементу before, а именно 100% высоту, выравнивание по центру и модель строчного блока. Так же само и у блока ставится модель строчного блока, выравнивание по центру. Чтобы блок не «падал» под псевдо-элемент, когда размеры первого больше чем родителя, указываем родителю white-space: nowrap и font-size: 0, после чего у блока отменяем эти стили следующими — white-space: normal. В данном примере font-size: 0 нужен для того, чтобы убрать образовавшийся пробел между родителем и блоком в связи с форматированием кода. Пробел можно убрать и иными способами, но лучшим считается просто его не допускать.
либо, если вам нужно, чтобы родитель занимал только высоту и ширину окна, а не всей страницы:
Вариант 5. Flexbox.
Одним из самых простых и элегантных способов является использования flexbox. Но имейте ввиду, что центральное позиционирование сохраняется даже если родительский блок меньше дочернего, последний будет выходить за рамки и обрезаться.
В случае, если при уменьшении родительского блока дочерний не должен обрезаться по краям, используйте авто маржины:
Вариант 6. Transform.
Подходит в случае если мы ограничены структурой, и нет возможности манипулировать родительским элементом, а блок выровнять как-то нужно. На помощь придёт css функция translate() . При значение 50% абсолютное позиционирование расположит верхний левый угол блока точно по центру, затем отрицательное значение translate сдвинет блок относительно своих собственных размеров. Учтите, что могут всплыть негативные эффекты в виде размытых граней или начертания шрифта. Также подобный способ может привести к проблемах с вычислением положения блока с помощью java-script’а. Иногда для компенсации потери 50% ширины из-за использования css свойства left может помочь заданное у блока правило: margin-right: -50%; .
Вариант 7. Кнопка.
Пользователь azproduction предложил вариант, где блок обрамляется в тег button. Кнопка имеет свойство центрировать всё, что находится у неё внутри, а именно элементы строчной и блочно-строчной (inline-block) модели. На практике использовать не рекомендую.
Бонус
Используя идею 4-го варианта, можно задавать внешние отступы для блока, и при этом последний будет адекватно отображаться в окружении скроллбаров.
Пример: jsfiddle.net/serdidg/ugnp8ry7.
Так же можно выравнивать картинку по центру, и в случае если картинка больше родителя, масштабировать её по размеру родителя.
Пример: jsfiddle.net/serdidg/Lhpa1s70.
Пример с большой картинкой: jsfiddle.net/serdidg/tor2yudn.
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.