Css margin auto display inline block

Особенности блоков с display:inline-block

В спецификации HTML представлены теги, которые являются изначально либо строчными (свойство display имеет значение inline), либо блочные (display: block). Однако с выходом стандарта CSS3 появилась возможность изменять отображение элемента на строчно-блочное (display: inline-block).

По сути строчно-блочные элементы являются чем-то средним между строчными и блочными. То есть они имеют свойства и тех, и других элементов, комбинируя их. Каким образом? — В тексте они ведут себя, как строчные элементы, т.е. занимают ровно столько места, сколько текста содержится в них (если не заданы ширина или отступы), однако при назначении свойств box-модели, интерпретируют их, как блочные элементы.

Лучше всего это можно продемонстрировать на примере. В файле ниже в двух колонках с одинаковым текстом выделены одни и те же словосочетания. Выделения находятся в элементах span с классом inline слева и inline-block справа. Для этих классов заданы общие правила:

Но в левой колонке все span имеют свойство display: inline , которое назначено для них в спецификации по умолчанию. А для span в правой колонке задан display: inline-block .

Можно заметить, что за счет внутренних отступов ( padding ) слева цветные выделения накладываются друг на друга, кое-где перекрывая текст, а это и некрасиво, и нечитабельно. Что касается внешних отступов (margin), то сверху и снизу для span в левой колонке они просто игнорируются, и только слева и справа отодвигают текст от соседнего.

В правой колонке ситуация несколько иная — здесь все элементы span визуально отделены от соседнего текста, причем margin-ы работает по всем 4-м сторонам, а padding не приводят к перекрыванию текста выше. Выделенные блоки с большим количеством текста выглядят именно как блочные элементы, а те, где текста мало вписываются в текст, но за счет margin-ов увеличивают высоту строки.

Сложно назвать оба вида форматирования красивыми, но из этого тестового упражнения можно сделать следующие выводы:

  1. строчным элементам с фоном не стоит задавать большие внутренние отступы ( padding ), иначе они перекрывают выше идущий текст. Максимально это должно быть 3px и при этом стоит увеличить высоту строки ( line-height ) для родительского элемента (абзаца или div-а, например);
  2. строчно-блочные элементы с фоном, размещенные в тексте, не должны содержать большие объемы текста, иначе они будут «вываливаться» из него наподобие цитат, или врезок. Лучше использовать этот тип отображения для элементов, которые предназначены для каких-либо оформительских целей, например, для буквиц, шрифтовых иконок, кнопок, ссылок и т.п.

Использование inline-block элементов для создания кнопок

Сделаем еще один небольшой сравнительный анализ. В примере ниже представлены ссылки, внешний вид которых с помощью css-стилей отображает их как кнопки. Но 2 из них имеют display: inline-block , одна — display: inline (по умолчанию заданный в спецификации для ссылки) и еще одна — display: block . Над каждой кнопкой подписано, каким образом она была отформатирована.

Читайте также:  Php присвоить массив элементу

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

Что касается кнопок с display: inline-block и display: inline , у которых размер был сформирован padding-ами, то при добавлении текста они просто расширяются. Оранжевая кнопка Sale, у которой размер имеет фиксированную ширину и высоту, увеличивается за счет добавленного текста вниз, хотя ни фон, ни рамка на этот текст не распространяются. Кнопка-ссылка с display: block изначально занимает всю ширину родительского элемента, поэтому добавление текста не влияет на ее размер на больших экранах. А вот на маленьких в ней текст за счет фиксированной высоты тоже выходит за пределы фона вниз. Еще можно заметить, что для желтой кнопки с display: inline несколько иначе определяются отступы от заголовка сверху — она расположена чуть выше всех остальных кнопок, хотя margin ни для одной из них в свойствах задан не был. Форматирование кнопок определялось такими свойствами:

Источник

Fixing CSS margin auto not working issues

CSS margin auto not centering your content? Check out these possible solutions to resolve your issue!

Jan 8, 2023 | Read time 12 minutes

🔔 Table of contents

Introduction

A common CSS trick to center a element within its parent is using the margin:auto property. For example, in the below, we can center the element of a class of .child with 500px within its parent element using the margin: 0 auto property:

To issues with margin: auto not working in CSS, you need to make sure that the element you are trying to center has a width and placed in a valid parent element with defined width. If the element still isn’t being centered as expected, you should check for any conflicting styles that might be overriding the margin: auto rule. You can also try using the text-align: center property on the parent element to center the child element. We can use different methods for centering the element, such as using absolute positioning or using flex.

How does margin:auto work?

We can center elements by using the margin auto property.

According to the specs, https://developer.mozilla.org/en-US/docs/Web/CSS/margin, margin is a shorthand CSS property that is supposed to replace the four:

So we can set margin without explitly writing out the above four properties like so:

The auto keyword just tells the browser to set the suitable margin to use for that element. Commonly used to center a element within its containing parent element!

1. Check for display:block

The most common reason why using margin:auto is not working for your designs is that the element’s display property is inline. This applies to elements like , , , etc.

With inline elements, they do not inherently have a width and therefore using margin auto will not work. This is setting margin:auto we are telling the browser to center a element based on the width.

To fix this, we just need to explicitly set the display CSS property to display:block . Any value that is not inline should work — eg display:inline-block, display:table, etc

Consider the following HTML structure:

Now the above will not work, because by default is a inline display ( display:inline ) and therefore cannot set the width. To fix this, we need to change it over to display:block and set the width.

(Note: we can also use min-width here)

Читайте также:  Javascript php или python

Tip: Consider using display:inline-block

Using display:inline-block is considered the sweetspot between trying to keep a element inline, but still able to control the width of the element!

2. Check for float CSS property

One thing to check is that we are not using the float property somewhere in our CSS stying. Adding float to a element removes it from the normal flow of the document. It allows you to place elements left or right side of a containing element and lets the text wrap around it.

Since margin:auto tells the browser to adjust margins based on the width, having something float will not work since the element will be outside of the control flow!

Consider the following HTML structure, we have a parent element and accidentally placed a float:right on the child element:

 In the above, even when we have margin:0 auto , adding a float:right will move the element outside of the normal document flow (ignoring margin auto calculations) and places it on the very right side of the parent container!

3. Check the element for a width value

To make sure that margin:auto is centering your elements correctly, we need to check that the element contains a explicit width property.

Consider the below HTML structure. We have a two divs — a parent div with .container class and we want to center the child div with CSS class .content .

 The above will not work because margin:auto relies on the width of the element. With elements, they have default of 100% width. So the parent element will be 100% of the page, and the child element ( .content ) will also have 100% width of the parent.

To fix this we need to add a width value for the DIV with the .content CSS class:

4. Check for conflicting styles

A common problem that you can encounter is using margin:auto on one styling can be overwritten by another style.

In this case, we need to check the specifity of the element you are trying to style.

For example, you could have a styling that is more specific or using the !important keyword.

Lets consider the following example. We want to make the child of a .container DIV font to have color of red:

Our CSS can have multiple

The above will not work, since the DIV with .content class got a inline style. Inline stylings has higher specitivity than CSS class selectors. So in this case, the margin:auto will not be applied, but the margin:1rem in the inline style — eg

XXX

What is CSS specificity?

Specificity is how browsers decide on which style to apply to which element. Based on the CSS selector is an order in which styles will be applied!

Generally, selectors with IDs will override classes. In turn, CSS selectors with classes will override pseudo-classes such as :last-child!

5. Check for browser support

Margin auto is widely available across modern browsers.

The margin auto property was initially used to center elements within a HTML container before flex or grid layouts came along. So if you are trying to support old browsers (such as IE10 or below) you might need to consider reverting back to margin:auto from your flex layouts!

One thing of note is that margin auto is not available in quirks mode for browsers like IE10 or below! Quirks mode is just a mode for browser to support legacy browsers such as Netscape and IE5 before the advent of W3C standards.

Typically we can trigger quirks mode by not including the tag. Any HTML file that has the tag will tell browsers that your page uses full standards mode.

Using margin:auto to center vertically

A common question or confusion is trying to use margin:auto to center a element vertically. Based on the previous CSS2 specification (https://www.w3.org/TR/CSS2/visudet.html#Computing_heights_and_margins) we cannot center it vertically since margin-top:auto and margin-bottom:auto the used value would compute to zero.

Consider the following HTML structure for the below hacks:

Now when we try to center the DIV with .content class vertically, it does not seem to work (even when we follow the above steps)
 We can fix this using the two hacks below:

1. Vertically center using margin auto position absolute hack

We can vertically center the .content DIV with the position absolute hack. First we need to add a CSS position property for the .container DIV — eg position:relative .

Then for our .content DIV, we can add the following hack of setting the position to absolute and top/bottom/left/right to zero:

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

So our final CSS will look like:

Margins work particularly well with flexbox — especially dealing with margin:auto. Auto margins on flex items have an effect very similar to auto margins in block flow — It is described in the specs here:

So we can expect similar behaviour as using display:block — since “any positive free space is distributed to auto margins in that dimension”

Summary

In this post we looked at using margin:auto to center elements in CSS. There are a few gotchas when using this technique. To center a element with margin:auto, we need to specify explicitly the width of the element. Additionally, the element should not be a inline element (eg , , etc). Inline elements have default display:inline — for margin:auto to work it needs to have display:block or display:inline-block .

We also looked at a few ways to make margin:auto work to center a element vertically. We can do this using the position absolute hack or making the parent container flex — using display:flex .

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

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