- CSS Margins
- CSS Margins
- Margin — Individual Sides
- Example
- Margin — Shorthand Property
- Example
- Example
- Example
- Example
- The auto Value
- Example
- The inherit Value
- Example
- All CSS Margin Properties
- margin-right
- Try it
- Syntax
- Values
- Formal definition
- Formal syntax
- margin
- Интерактивный пример
- Составные свойства
- Синтаксис
- Значения
- Формальное определение
- margin-inline
- Try it
- Constituent properties
- Syntax
- Values
- Formal definition
- Formal syntax
- Examples
- Setting inline start and end margins
- CSS
- HTML
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
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 margin-right
The margin-right CSS property sets the margin area on the right side of an element. A positive value places it farther from its neighbors, while a negative value places it closer.
Try it
The vertical margins of two adjacent boxes may fuse. This is called margin collapsing.
Syntax
/* values */ margin-right: 20px; /* An absolute length */ margin-right: 1em; /* relative to the text size */ margin-right: 5%; /* relative to the nearest block container's width */ /* Keyword values */ margin-right: auto; /* Global values */ margin-right: inherit; margin-right: initial; margin-right: revert; margin-right: revert-layer; margin-right: unset;
The margin-right property is specified as the keyword auto , or a , or a . Its value can be positive, zero, or negative.
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 right margin receives a share of the unused horizontal space, as determined mainly by the layout mode that is used. If the values of margin-left and margin-right are both auto , the calculated space is evenly distributed. This table summarizes the different cases:
Value of display Value of float Value of position Computed value of auto Comment inline , inline-block , inline-table any static or relative 0 Inline layout mode block , inline , inline-block , block , table , inline-table , list-item , table-caption any static or relative 0 , except if both margin-left and margin-right are set to auto . In this case, it is set to the value centering the element inside its parent. Block layout mode block , inline , inline-block , block , table , inline-table , list-item , table-caption left or right static or relative 0 Block layout mode (floating element) any table-* , except table-caption any any 0 Internal table-* elements don’t have margins, use border-spacing instead any, except flex , inline-flex , or table-* any fixed or absolute 0 , except if both margin-left and margin-right are set to auto . In this case, it is set to the value centering the border area inside the available width , if fixed. Absolutely positioned layout mode flex , inline-flex any any 0 , except if there is any positive horizontal free space. In this case, it is evenly distributed to all horizontal auto margins. Flexbox layout mode Formal definition
Initial value 0 Applies to all elements, except elements with table display types other than table-caption , table and inline-table . It also applies to ::first-letter and ::first-line . Inherited no Percentages refer to the width of the containing block Computed value the percentage as specified or the absolute length Animation type a length Formal syntax
margin
CSS свойство margin определяет внешний отступ на всех четырёх сторонах элемента. Это сокращение, которое устанавливает все отдельные поля одновременно: margin-top , margin-right , margin-bottom и margin-left .
Интерактивный пример
Составные свойства
Данное свойство является сокращением для следующих CSS свойств:
Синтаксис
/* Применяется ко всем четырём сторонам */ margin: 1em; margin: -3px; /* по вертикали | по горизонтали */ margin: 5% auto; /* сверху | горизонтально | снизу */ margin: 1em auto 2em; /* сверху | справа | снизу | слева */ margin: 2px 1em 0 auto; /* Глобальные значения */ margin: inherit; margin: initial; margin: unset;
Свойство margin может быть задано с использованием одного, двух, трёх или четырёх значений. Каждое значение имеет тип , или является ключевым словом auto . Каждое значение может быть положительным, отрицательным или равным нулю.
- Когда определено одно значение, такое значение определено для всех четырёх сторон.
- Когда определены два значения, то первое значение определяет внешний отступ для верхней и нижней стороны, а второе значение определяет отступ для левой и правой стороны.
- Когда определены три значение, то первое значение определяет внешний отступ для верхней стороны, второе значение определяет внешний отступ для левой и правой стороны, а третье значение определяет отступ для нижней стороны.
- Когда определены четыре значения, они определяют внешние отступы для верхней стороны, справа, снизу и слева в рассмотренном порядке (по часовой стрелке).
Значения
Размер отступа как фиксированное значение.
Размер отступа в процентах относительно ширины родительского блока.
Браузер выбирает подходящее значение для использования. Например, в некоторых случаях это значение может быть использовано для центрирования элемента.
Формальное определение
- margin-bottom : 0
- margin-left : 0
- margin-right : 0
- margin-top : 0
- margin-bottom : процент, как указан, или абсолютная длина
- margin-left : процент, как указан, или абсолютная длина
- margin-right : процент, как указан, или абсолютная длина
- margin-top : процент, как указан, или абсолютная длина
margin-inline
The margin-inline CSS shorthand property is a shorthand property that defines both the logical inline start and end margins of an element, which maps to physical margins depending on the element’s writing mode, directionality, and text orientation.
Try it
Constituent properties
This property is a shorthand for the following CSS properties:
Syntax
/* values */ margin-inline: 10px 20px; /* An absolute length */ margin-inline: 1em 2em; /* relative to the text size */ margin-inline: 5% 2%; /* relative to the nearest block container's width */ margin-inline: 10px; /* sets both start and end values */ /* Keyword values */ margin-inline: auto; /* Global values */ margin-inline: inherit; margin-inline: initial; margin-inline: revert; margin-inline: revert-layer; margin-inline: unset;
This property corresponds to the margin-top and margin-bottom , or the margin-right and margin-left properties, depending on the values defined for writing-mode , direction , and text-orientation .
The margin-inline property may be specified using one or two values.
- When one value is specified, it applies the same margin to both start and end.
- When two values are specified, the first margin applies to the start, the second to the end.
Values
The margin-inline property takes the same values as the margin property.
Formal definition
- margin-inline-start : 0
- margin-inline-end : 0
- margin-inline-start : if specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto
- margin-inline-end : if specified as a length, the corresponding absolute length; if specified as a percentage, the specified value; otherwise, auto
Formal syntax
Examples
Setting inline start and end margins
CSS
div background-color: yellow; width: 120px; height: auto; border: 1px solid green; > p margin: 0; margin-inline: 20px 40px; background-color: tan; > .verticalExample writing-mode: vertical-rl; >
HTML
div> p>Example textp> div> div class="verticalExample"> p>Example textp> div>
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
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.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.