Выравнивание по центру css position absolute

How to align absolutely positioned element to center?

I am trying to stack two canvas together and make it a double layers canvas. I’ve saw an example here:

But i would like to set both of the canvas align at the center of the screen. If i set the value of left as a constant, while I change the orientation of the screen (as I’m doing aps on iPad) the canvas won’t remain at the middle of the screen like how it act in

8 Answers 8

If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.

position:absolute; left:0; right:0; margin-left:auto; margin-right:auto; 

You can use change the left or right values to move the object out of the center, fixed. Using left: 80px; will move the object 40px (!) to the right of the center.

If you want to center align an element without knowing it’s width and height do:

position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 

It’s a nice trick, but there is a little caveat in your approach. If the element’s width is not set but it has inline content that’s wider than 50% of the parent’s width, then the extra 50% offset from the left will extrapolate the parent’s width, breaking the content to the next lines to avoid overflow. But it’s possible to keep the content inline while using this approach by setting in the element the white-space attribute to nowrap . Try that in this JSFiddle.

Читайте также:  Css style fonts examples

try this method, working fine for me

position: absolute; left: 50%; transform: translateX(-50%); 

To align elements with knowing width and height use the solution below:

position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; 

For elements with unknown width and height use the following solution:

position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); 
left:50%; top:50%; margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */ 

Not sure if it’ll work, but it’s worth a try.

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan.

Ya I have tried this, but the canvas «start» from middle but not «placed» in the middle of the screen. Is there anyway to set left:50% and move the canvas to left again?

All you have to do is make sure your parent has position:relative , and set a height and width for the element you want centered. Use the following CSS:

Only solution that works for me. Parent is set to flex, flex-grow & overflow. Child was positioned out of frame for images larger than the parent. It didn’t seem to be aware of the parent’s width. It’s fixed now. BIG thanks!

Move the parent div to the middle with

left: 50%; top: 50%; margin-left: -50px; 

Move the second layer over the other with

position: relative; left: -100px; 

There’s another approach I’d like to share, may be useful if your are building something from scratch.

I was strugueling with this same situation but when I used the methods above it didn’t work because I had a class on every label that changes the background when scrooling.

I created a method on Javascript to calculate the size of the element and viewport to locate properly every time the viewport size changes.

function setOnCenter(element) < let elm = $("#" + element); let currentlyViewportWidth = $(window).width(); let unitWidthViewport = currentlyViewportWidth / 100; let pxSizeText = elm.outerWidth(); let percentSizeText = pxSizeText / unitWidthViewport; let halfPercentSizeText = percentSizeText / 2; let result = 50 - halfPercentSizeText; elm.css(< width: pxSizeText + 'px', left: result + '%'>); > window.addEventListener("resize", function (event) < setOnCenter('stuff_text'); >) 

Of course the setOnCenter method must be execute when document is ready. If there something to improved I’d be glad to read it.

Источник

How to Center an Absolute Positioned Element Vertically and Horizontally with CSS

Dillion Megida

Dillion Megida

How to Center an Absolute Positioned Element Vertically and Horizontally with CSS

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:

image-32

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:

image-31

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?

image-33

It definitely does not. As an absolute element, it loses its flow in the container. Maybe a left: auto and right: auto then:

image-34

Still nothing. At this point, you may be tempted to use hardcoded values:

.blue-block, .black-block < display: none; >.green-block

image-35

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.

image-36

The left takes more precendence because the container displays elements from left to right.

The beauty comes in with the next style:

image-37

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:

image-39

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:

image-38

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
  • Требует множество разнообразных префиксов для корректной работы в современных браузерах
  • Возможные проблемы производительности

Итог

Каждый способ имеет преимущества и недостатки. По сути, выбор сводится к выбору браузеров, которые должны поддерживаться

Источник

Оцените статью