Html margin left and right auto

margin

The margin CSS shorthand property sets the margin area on all four sides of an element.

Try it

Constituent properties

This property is a shorthand for the following CSS properties:

Syntax

/* Apply to all four sides */ margin: 1em; margin: -3px; /* top and bottom | left and right */ margin: 5% auto; /* top | left and right | bottom */ margin: 1em auto 2em; /* top | right | bottom | left */ margin: 2px 1em 0 auto; /* Global values */ margin: inherit; margin: initial; margin: revert; margin: revert-layer; margin: unset; 

The margin property may be specified using one, two, three, or four values. Each value is a , a , or the keyword auto . Negative values draw the element closer to its neighbors than it would be by default.

  • When one value is specified, it applies the same margin to all four sides.
  • When two values are specified, the first margin applies to the top and bottom, the second to the left and right.
  • When three values are specified, the first margin applies to the top, the second to the right and left, the third to the bottom.
  • When four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise).
Читайте также:  Класс bigdecimal java округление

Values

The size of the margin as a fixed value.

The size of the margin as a percentage, relative to the inline size (width in a horizontal language, defined by writing-mode ) of the containing block.

The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

Description

This property can be used to set a margin on all four sides of an element. Margins create extra space around an element, unlike padding , which creates extra space within an element.

The top and bottom margins have no effect on non-replaced inline elements, such as or .

Horizontal centering

To center something horizontally in modern browsers, you can use display : flex; justify-content : center; .

However, in older browsers like IE8-9 that do not support Flexible Box Layout, these are not available. In order to center an element inside its parent, use margin: 0 auto; .

Margin collapsing

Elements’ top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins. See Mastering margin collapsing for more information.

Formal definition

  • margin-bottom : 0
  • margin-left : 0
  • margin-right : 0
  • margin-top : 0
  • margin-bottom : the percentage as specified or the absolute length
  • margin-left : the percentage as specified or the absolute length
  • margin-right : the percentage as specified or the absolute length
  • margin-top : the percentage as specified or the absolute length

Formal syntax

Examples

Simple example

HTML

div class="center">This element is centered.div> div class="outside">This element is positioned outside of its container.div> 

CSS

.center  margin: auto; background: lime; width: 66%; > .outside  margin: 3rem 0 0 -3rem; background: cyan; width: 66%; > 

More examples

margin: 5%; /* All sides: 5% margin */ margin: 10px; /* All sides: 10px margin */ margin: 1.6em 20px; /* top and bottom: 1.6em margin */ /* left and right: 20px margin */ margin: 10px 3% -1em; /* top: 10px margin */ /* left and right: 3% margin */ /* bottom: -1em margin */ margin: 10px 3px 30px 5px; /* top: 10px margin */ /* right: 3px margin */ /* bottom: 30px margin */ /* left: 5px margin */ margin: 2em auto; /* top and bottom: 2em margin */ /* Box is horizontally centered */ margin: auto; /* top and bottom: 0 margin */ /* Box is horizontally centered */ 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Introduction to the CSS basic box model
  • Margin collapsing
  • margin-top , margin-right , margin-bottom , and margin-left
  • The mapped logical properties: margin-block-start , margin-block-end , margin-inline-start , and margin-inline-end and the shorthands margin-block and margin-inline

Found a content problem with this page?

This page was last modified on Jul 18, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

CSS margin:auto — Как это работает?

Использование margin:auto , чтобы отцентрировать блочный элемент по горизонтали, это хорошо известный способ. Но задумывались ли вы, как это работает?

Результат действия значения auto зависит типа элемента и контекста. Для отступов сверху CSS auto может означать одно из двух: занять все свободное пространство или 0 пикселей. В зависимости от этого будет задаваться различная структура.

«auto» — занять все доступное пространство

Это наиболее распространенный способ использования auto для отступов. Если мы задаем auto для левого и правого отступов одного элемента, они равномерно займут все доступное в контейнере по горизонтали пространство. Таким образом элемент расположится по центру.

Это работает только для горизонтальных отступов. Но не будет работать для плавающих и строчных элементов. А также для абсолютно и фиксировано позиционированных элементов.

Имитация плавающего поведения через распределение доступного пространства

auto поровну распределяет все свободное пространство между правым и левым отступами. Но что произойдет, если мы зададим это значение только для одного из отступов? Тогда он займет все доступное пространство, и элемент будет смещен к правому или левому краю.

«auto» — задать 0 пикселей

Как упоминалось выше, auto не работает для плавающих, строчных и абсолютно позиционированных элементов. Для них уже определена структура, так что в использовании margin auto нет смысла.

Это будет только нарушать изначальную структуру. В том числе и для отступа текста сверху CSS . Следовательно, auto будет задавать значение 0 пикселей для отступов этих элементов.

auto также не будет работать для стандартного блочного элемента, если для него не задана ширина. Во всех примерах, приведенных мной, для элементов была задана ширина.

Значение auto будет определять отступ в 0 пикселей, когда для блочного элемента задана ширина auto или 100% . Обычно он занимает всю ширину контейнера, следовательно, на ширину отступа останется 0 пикселей.

Что происходит с вертикальными отступами со значением auto?

auto и для отступа сверху CSS , и для нижнего отступа всегда вычисляется как 0 пикселей ( за исключением абсолютно позиционированных элементов ). В спецификации W3C указано следующее:

«Если для “margin-top” или “margin-bottom” задано «auto», для них используется значение, равное 0″.

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

А может быть связано с той же причиной, по которой они решили добавить исключение для абсолютно позиционированных элементов, которые можно расположить по центру вертикально относительно общей высоты страницы.

Или из-за эффекта объединения отступов ( слияния отступов соседних элементов ). Это еще одно исключение из данного правила определения вертикальных отступов.

Центрирование абсолютно позиционированных элементов

Так как для абсолютно позиционированных элементов введено исключение, можно использовать значение auto , чтобы выровнять их по центру вертикально и горизонтально. Но сначала нужно выяснить, когда margin:auto будет работать именно так для отступа сверху CSS .

В другой спецификации W3C сказано:

«Если для всех трех позиций (“left”, “width” и “right”) задано значение «auto», сначала установите 0 для “margin-left” и “margin-right. »
» Если «auto» задано только для “margin-left” и “margin-right», тогда решите уравнение с дополнительным условием, чтобы для обоих отступов была задана одинаковая ширина».

Здесь довольно подробно описана ситуация, касающаяся значения auto для горизонтальных отступов. Чтобы эти отступы имели одинаковый размер, для left , width и right не должно задаваться значение auto ( их значение по умолчанию ). Чтобы отцентрировать элемент по горизонтали, нужно задать определенное значение для ширины абсолютно позиционируемого элемента, а left и right при этом должны иметь равные значения.

В спецификации также упоминается что-то подобное и для отступов сверху CSS div.

«Если для «top», «height» и «bottom» задано значение «auto» , установите для «top» позицию static. «

«Если для одной из трех позиций не установлено значение «auto»: если для «top» и «bottom» установлено значение «auto», решите уравнение с дополнительным условием, чтобы задать для этих отступов одинаковые значения».

Следовательно, чтобы отцентрировать по вертикали абсолютно позиционируемый элемент top , height и bottom не должны иметь значение auto .

Теперь, объединив все это, мы получим следующее:

Заключение

Если вам требуется сместить элемент на странице вправо или влево без контейнерных элементов ( например, как в случае с float ), помните, что есть возможность использовать для отступов значение auto .

Преобразование элемента в абсолютно позиционируемый только для того, чтобы отцентрировать его по вертикали ( отступы сверху CSS ), не лучшая идея. Существуют и другие варианты, такие как flexbox и CSS transform , которые больше подходят для этого.

Вадим Дворников автор-переводчик статьи « CSS – margin auto – How it Works »

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

Источник

CSS Margins

Margins are used to create space around elements, outside of any defined borders.

CSS Margins

The CSS margin properties are used to create space around elements, outside of any defined borders.

With CSS, you have full control over the margins. There are properties for setting the margin for each side of an element (top, right, bottom, and left).

Margin — Individual Sides

CSS has properties for specifying the margin for each side of an element:

All the margin properties can have the following values:

  • auto — the browser calculates the margin
  • length — specifies a margin in px, pt, cm, etc.
  • % — specifies a margin in % of the width of the containing element
  • inherit — specifies that the margin should be inherited from the parent element

Tip: Negative values are allowed.

Example

Set different margins for all four sides of a

element:

Margin — Shorthand Property

To shorten the code, it is possible to specify all the margin properties in one property.

The margin property is a shorthand property for the following individual margin properties:

If the margin property has four values:

  • margin: 25px 50px 75px 100px;
    • top margin is 25px
    • right margin is 50px
    • bottom margin is 75px
    • left margin is 100px

    Example

    Use the margin shorthand property with four values:

    If the margin property has three values:

    • margin: 25px 50px 75px;
      • top margin is 25px
      • right and left margins are 50px
      • bottom margin is 75px

      Example

      Use the margin shorthand property with three values:

      If the margin property has two values:

      • margin: 25px 50px;
        • top and bottom margins are 25px
        • right and left margins are 50px

        Example

        Use the margin shorthand property with two values:

        If the margin property has one value:

        Example

        Use the margin shorthand property with one value:

        The auto Value

        You can set the margin property to auto to horizontally center the element within its container.

        The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.

        Example

        The inherit Value

        Example

        div <
        border: 1px solid red;
        margin-left: 100px;
        >

        All CSS Margin Properties

        Property Description
        margin A shorthand property for setting all the margin properties in one declaration
        margin-bottom Sets the bottom margin of an element
        margin-left Sets the left margin of an element
        margin-right Sets the right margin of an element
        margin-top Sets the top margin of an element

        Источник

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