Html display block align center

Web Style Sheets CSS tips & tricks

The most common and (therefore) easiest type of centering is that of lines of text in a paragraph or in a heading. CSS has the property ‘text-align’ for that:

renders each line in a P or in a H2 centered between its margins, like this:

The lines in this paragraph are all centered between the paragraph’s margins, thanks to the value ‘center’ of the CSS property ‘text-align’.

Centering a block or image

Sometimes it is not the text that needs to be centered, but the block as a whole. Or, phrased differently: we want the left and right margin to be equal. The way to do that is to set the margins to ‘auto’. This is normally used with a block of fixed width, because if the block itself is flexible, it will simply take up all the available width. Here is an example:

This rather narrow block of text is centered. Note that the lines inside the block are not centered (they are left-aligned), unlike in the earlier example.

This is also the way to center an image: make it into block of its own and apply the margin properties to it. For example:

some random image

The following image is centered:

Centering vertically

CSS level 2 doesn’t have a property for centering things vertically. There will probably be one in CSS level 3 (see below ). But even in CSS2 you can center blocks vertically, by combining a few properties. The trick is to specify that the outer block is to be formatted as a table cell, because the contents of a table cell can be centered vertically.

DIV.container < min-height: 10em; display: table-cell; vertical-align: middle >. 
This small paragraph.

This small paragraph is vertically centered.

Centering vertically in CSS level 3

CSS level 3 offers other possibilities. At this time (2014), a good way to center blocks vertically without using absolute positioning (which may cause overlapping text) is still under discussion. But if you know that overlapping text will not be a problem in your document, you can use the ‘transform’ property to center an absolutely positioned element. For example:

This paragraph is vertically centered.

For a document that looks like this:

the style sheet looks like this:

div.container3 < height: 10em; position: relative > /* 1 */ div.container3 p < margin: 0; position: absolute; /* 2 */ top: 50%; /* 3 */ transform: translate(0, -50%) > /* 4 */
  1. Make the container relatively positioned, which declares it to be a container for absolutely positioned elements.
  2. Make the element itself absolutely positioned.
  3. Place it halfway down the container with ‘top: 50%’. (Note that 50%’ here means 50% of the height of the container.)
  4. Use a translation to move the element up by half its own height. (The ‘50%’ in ‘translate(0, -50%)’ refers to the height of the element itself.)
Читайте также:  Php throw error warning

Recently (since about 2015), another technique has also become available in several CSS implementations. It is based on the new ‘flex’ keyword for the ‘display’ property. This keyword is meant for use in graphical user interfaces (GUIs), but nothing stops you from using it in a document, if the document happens to have the right structure.

This paragraph is vertically centered.

the style sheet looks like this:

div.container5 < height: 10em; display: flex; align-items: center > div.container5 p

Centering vertically and horizontally in CSS level 3

We can extend both methods to center horizontally and vertically at the same time.

A side-effect of making the paragraph absolutely positioned is that it is then only as wide as it needs to be (unless we give it an explicit width, of course). In the example below, that’s precisely what we want: We center a paragraph with just one word (“Centered!”), so the width of the paragraph should be exactly the width of that word.

The yellow background is there to show that the paragraph is indeed only as wide as its contents. We assume the same mark-up as before:

The style sheet is similar to the previous example with respect to the vertical centering. But we now move the element halfway across the container as well, with ‘left: 50%’, and at the same time move it leftwards by half its own width in the ‘translate’ transformation:

div.container4 < height: 10em; position: relative >div.container4 p < margin: 0; background: yellow; position: absolute; top: 50%; left: 50%; margin-right: -50%; transform: translate(-50%, -50%) >

The next example below explains why the ‘margin-right: -50%’ is needed.

When the CSS formatter supports ‘flex’, it’s even easier:

div.container6 < height: 10em; display: flex; align-items: center; justify-content: center > div.container6 p

i.e., the only addition is the ‘justify-content: center’. Just like ‘align-items’ determines the vertical alignment of the container’s contents, ‘justify-content’ determines the horizontal alignment. (It’s actually a bit more complex, as their names suggest, but in a simple case that’s how it works.) A side-effect of ‘flex’ is that the child element, the P in this case, is automatically made as small as possible.

Читайте также:  Enumerate python 3 пример

Centering in the viewport in CSS level 3

The default container for absolutely positioned elements is the viewport. (In case of a browser, that means the browser window). So centering an element in the viewport is very simple. Here is a complete example. (This example uses HTML5 syntax.)

   

Nicely centered

This text block is vertically centered.

Horizontally, too, if the window is wide enough.

You can see the result in a separate document.

The ‘margin-right: -50%’ is needed to compensate the ‘left: 50%’. The ‘left’ rule reduces the available width for the element by 50%. The renderer will thus try to make lines that are no longer than half the width of the container. By saying that the right margin of the element is further to the right by that same amount, the maximum line length is again the same as the container’s width.

Try resizing the window: You’ll see that each sentence is on one line when the window is wide enough. Only when the window is too narrow for the whole sentence will the sentence be broken over several lines. When you remove the ‘margin-right: -50%’ and resize the window again, you’ll see that the sentences will be broken already when the window is still twice as wide as the text lines.

Bert Bos, style activity lead
Copyright © 1994–2021 W3C ® Privacy policy

Created 5 May 2001;
Last updated Wed 06 Jan 2021 05:40:49 AM UTC

Источник

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

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

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

Источник

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