Css align div contents to center

Выравниваем блок по центру страницы

Очень часто стоит задача выровнять блок по центру страницы / экрана, да ещё и так, чтобы без ява-скрипта, без задания жёстких размеров или отрицательных отступов, ещё чтобы и скроллбары работали у родителя, если блок превышает его размеры. В сети ходят достаточно много однообразных примеров как выровнять блок по центру экрана. Как правило большинство из них основаны на одних принципах.

Ниже представлены основные способы решения задачи, их плюсы и минусы. Чтобы понимать суть примеров, рекомендую уменьшить высоту / ширину окошка 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 нужен для того, чтобы убрать образовавшийся пробел между родителем и блоком в связи с форматированием кода. Пробел можно убрать и иными способами, но лучшим считается просто его не допускать.

Читайте также:  Css cannot find servers

либо, если вам нужно, чтобы родитель занимал только высоту и ширину окна, а не всей страницы:

Вариант 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.

Источник

CSS Layout — Horizontal & Vertical Align

Setting the width of the element will prevent it from stretching out to the edges of its container.

The element will then take up the specified width, and the remaining space will be split equally between the two margins:

This div element is centered.

Example

Note: Center aligning has no effect if the width property is not set (or set to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

Example

Tip: For more examples on how to align text, see the CSS Text chapter.

Center an Image

To center an image, set left and right margin to auto and make it into a block element:

Paris

Example

Left and Right Align — Using position

One method for aligning elements is to use position: absolute; :

In my younger and more vulnerable years my father gave me some advice that I’ve been turning over in my mind ever since.

Читайте также:  Php прерывает цикл while

Example

Note: Absolute positioned elements are removed from the normal flow, and can overlap elements.

Left and Right Align — Using float

Another method for aligning elements is to use the float property:

Example

The clearfix Hack

Note: If an element is taller than the element containing it, and it is floated, it will overflow outside of its container. You can use the «clearfix hack» to fix this (see example below).

Without Clearfix

With Clearfix

Then we can add the clearfix hack to the containing element to fix this problem:

Example

Center Vertically — Using padding

There are many ways to center an element vertically in CSS. A simple solution is to use top and bottom padding :

Example

To center both vertically and horizontally, use padding and text-align: center :

I am vertically and horizontally centered.

Example

Center Vertically — Using line-height

Another trick is to use the line-height property with a value that is equal to the height property:

I am vertically and horizontally centered.

Example

.center <
line-height: 200px;
height: 200px;
border: 3px solid green;
text-align: center;
>

/* If the text has multiple lines, add the following: */
.center p line-height: 1.5;
display: inline-block;
vertical-align: middle;
>

Center Vertically — Using position & transform

If padding and line-height are not options, another solution is to use positioning and the transform property:

I am vertically and horizontally centered.

Example

.center <
height: 200px;
position: relative;
border: 3px solid green;
>

.center p margin: 0;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
>

Tip: You will learn more about the transform property in our 2D Transforms Chapter.

Center Vertically — Using Flexbox

You can also use flexbox to center things. Just note that flexbox is not supported in IE10 and earlier versions:

Example

.center <
display: flex;
justify-content: center;
align-items: center;
height: 200px;
border: 3px solid green;
>

Tip: You will learn more about Flexbox in our CSS Flexbox Chapter.

Источник

How to Center a Div with CSS

Ihechikara Vincent Abba

Ihechikara Vincent Abba

How to Center a Div with CSS

There are a few common coding problems you might encounter when you start practicing what you’ve learned by building projects.

One common problem you’ll face as a web developer is how to place an element at the center of a page or within an element acting as its container. It’s the ubiquitous «How do I center a div?» problem.

In this article, we’ll see how we can center elements using various CSS properties. We’ll see code examples in each section and a visual representation of the elements in all the examples.

How to Center a Div Using the CSS Flexbox Property

In this section, we’ll see how we can use the CSS Flexbox property to center an element horizontally, vertically, and at the center of a page/container.

You can use an image if you prefer that, but we’ll just use a simple circle drawn with CSS. Here’s the code:

Читайте также:  Java new main method

Screenshot--276-

Positioning with Flexbox requires that we write the code in the parent or container element’s class.

How to Center a Div Horizontally Using Flexbox

Now we’ll write the code to center the div element horizontally. We’re still making use of the circle we created above.

We’ve added two lines of code to center the circle horizontally. These are the lines we added:

display: flex; justify-content: center;

display: flex; allows us to use Flexbox and its properties, while justify-content: center; aligns the circle to the center horizontally.

Here is the position of our circle:

Screenshot--278-

How to Center a Div Vertically Using Flexbox

What we’ll be doing in this section is similar to the last one, except for one line of code.

In this example, we used align-items: center; to center the circle vertically. Recall that we are required to write display: flex; first before specifying the direction.

Here’s the position of our circle:

Screenshot--280-

How to Position a Div at the Center Using Flexbox

In this section, we’ll position the circle at the center of the page using both the horizontal and vertical alignment properties of CSS Flexbox. Here’s how:

Here are the three lines of code we added to the container class above:

display: flex; justify-content: center; align-items: center;

As expected, we begin with display: flex; which allows us to use Flexbox in CSS. We then used both the justify-content (horizontal alignment) and align-items (vertical alignment) properties to position the circle at the center of the page.

Here is the position of our circle:

Screenshot--282-

How to Center a Div Horizontally Using the CSS margin Property

In this section, we’ll be using the margin property to center our circle horizontally.

Let’s create our circle again.

Screenshot--276-

This time we’ll write the code in the circle class. Here’s how:

All we’ve added is the margin: 0 auto; line of code to the circle class.

Let’s have a look at the position of the circle:

Screenshot--278--1

How to Center Text Horizontally Using the CSS text-align Property

In this section, we’ll see how to center text horizontally.

This method only works when we are working with text written within an element.

In the example above, we have created a div with a class of container and a h1 element with some text. This is what it looks like at the moment:

Screenshot--272-

In other to align the text in the h1 element at the center of the page, we had to use the text-align property, giving it a value of center . Here’s what it looks like now in the browser:

Screenshot--274-

Conclusion

In this article, we saw how we can center elements horizontally, vertically, and at the center of the page using Flexbox and the margin and text-align properties in CSS.

In each section, we saw both a code example and a visual representation of what the code does.

Источник

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