- CSS margin-left Property
- Syntax
- Example of the margin-left property defined as «px»:
- Result
- Example of the margin-left property defined as «em»:
- Example of the margin-left property defined as «px», «em» and «%»:
- Values
- Browser support
- margin-left
- Интерактивный пример
- Синтаксис
- Значения
- Формальный синтаксис
- Примеры
- Спецификации
- Поддержка браузерами
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- margin-left¶
- Демо¶
- Синтаксис¶
- Значения¶
- Спецификации¶
- Описание и примеры¶
- 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-left
- Синтаксис
- Значения
- Объектная модель
- Браузеры
CSS margin-left Property
The margin-left property is used to define how much the left margin of the element will be set.
There are some rare situations when width, margin-left , border, padding, the content area and margin-right are defined. When it happens, the margin-left will be ignored and it will be set as if the auto value is defined.
The margin-left property is defined as the keyword , or a . Its value may be negative, positive or zero.
Initial Value | 0 |
Applies to | All elements. It also applies to ::first-letter. |
Inherited | No. |
Animatable | Yes. Left margin of the element is animatable. |
Version | CSS2 |
DOM Syntax | object.style.marginLeft = «20px»; |
Syntax
margin-left: length | auto | initial | inherit;
Example of the margin-left property defined as «px»:
html> html> head> title>Title of the document title> style> .left < margin-left: 25px; > style> head> body> h2>Margin-left property example h2> p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> p class="left">Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> body> html>
Result
Example of the margin-left property defined as «em»:
html> html> head> title>Title of the document title> style> .left < margin-left: 8em; > style> head> body> h2>Margin-left property example h2> p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> p class="left">Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> body> html>
Example of the margin-left property defined as «px», «em» and «%»:
html> html> head> title>Title of the document title> style> p.p1 < margin-left: 6em; > p.p2 < margin-left: 40px; > p.p3 < margin-left: 10%; > style> head> body> h2>Margin-left property example h2> p>No specified margin. p> p class="p1"> Left margin is set to 6em. p> p class="p2">Left margin is set to 40px. p> p class="p3">Left margin is set to 10%. p> p>No specified margin p> body> html>
Values
Value | Description | Play it |
---|---|---|
auto | Sets the left margin. It is the default value of this property. | Play it » |
length | Defines a left margin in px, pt, cm, etc. Default value is 0. | Play it » |
% | Sets the left margin in % of containing element. | Play it » |
initial | Makes the property use its default value. | Play it » |
inherit | Inherits the property from its parents element. |
Browser support
margin-left
Свойство CSS margin-left устанавливает внешний отступ слева от элемента. Положительное значение увеличивает расстояние между соседними элементами, тогда как отрицательное — сокращает.
Интерактивный пример
Вертикальные внешние отступы двух соседних блоков могут схлопнуться. Это называется схлопыванием внешних отступов.
В редких случаях, когда ширина (т.е., когда все значения width , margin-left , border , padding , область содержимого, и margin-right определены), margin-left игнорируется, и будет иметь такое же расчётное значение, как и auto .
Синтаксис
/* значения */ margin-left: 10px; /* абсолютная длина */ margin-left: 1em; /* относительно размера текста */ margin-left: 5%; /* относительно ширины родительского блока */ /* Значения-ключевые слова */ margin-left: auto; /* Глобальные значения */ margin-left: inherit; margin-left: initial; margin-left: unset;
Свойство margin-left может быть выражено как ключевое слово auto , как , или как . Значение может быть положительным, нулевым или отрицательным.
Значения
-
- : Размер отступа — фиксированная величина.
- : Размер отступа в процентах — размер относительно длины родительского блока.
-
: Внешний отступ слева получает долю неиспользованного горизонтального пространства, определяется в основном выбранным способом разметки. Если значения margin-left и margin-right одновременно установлены как auto , расчётное пространство распределяется равномерно. Эта таблица кратко излагает различные: Значение display Значение float Значение position Расчётное значение auto Комментарий inline , inline-block , inline-table любое static или relative 0 Строчный способ разметки block , inline , inline-block , block , table , inline-table , list-item , table-caption любое static или relative 0 , кроме случаев, когда margin-left и margin-right установлены как auto . В этом случае устанавливается значение, центрирующее элемент внутри его родителя Блочный способ разметки block , inline , inline-block , block , table , inline-table , list-item , table-caption left или right static или relative 0 Блочный способ разметки (плавающие элементы) любое table-* , кроме table-caption любое любое 0 Внутренние table-* элементы не имеют отступов, вместо этого используйте border-spacing (en-US) любое, кроме flex , inline-flex , или table-* любое fixed или absolute 0 , кроме случаев, когда margin-left и margin-right установлены как auto . В этом случае, устанавливается значение центрирующее границы области внутри доступной width (ширины), если значение фиксировано. Способ разметки абсолютным позиционированием flex , inline-flex любое любое 0 , кроме случаев, когда есть положительное горизонтальное свободное пространство. В этом случае, распределяется равномерно по всем горизонтальным auto отступам. Способ разметки с помощью flexbox
Формальный синтаксис
Примеры
.content margin-left: 5%; > .sidebox margin-left: 10px; > .logo margin-left: -5px; >
Спецификации
Начальное значение 0 Применяется к все элементы, кроме элементов с табличным типом display , отличным от table-caption , table и inline-table . Это также применяется к ::first-letter и ::first-line . Наследуется нет Проценты ссылается на ширину содержащего блока Обработка значения процент, как указан, или абсолютная длина Animation type длина Поддержка браузерами
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. 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.margin-left¶
Свойство margin-left устанавливает величину отступа от левого края элемента.
Отступом является расстояние от внешнего края левой границы текущего элемента до внутренней границы его родительского элемента (рис. 1).
Демо¶
Синтаксис¶
1 2 3 4 5 6 7 8 9 10 11 12
/* values */ margin-left: 10px; /* An absolute length */ margin-left: 1em; /* relative to the text size */ margin-left: 5%; /* relative to the nearest block container's width */ /* Keyword values */ margin-left: auto; /* Global values */ margin-left: inherit; margin-left: initial; margin-left: unset;
Значения¶
Величину левого отступа можно указывать в пикселях (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.
auto Указывает, что размер отступов будет автоматически рассчитан браузером.
Применяется ко всем элементам
Спецификации¶
Описание и примеры¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
html> head> meta charset="utf-8" /> title>margin-lefttitle> style> .layer1 background-color: #d36037; /* Цвет фона */ > .layer2 margin-left: 20%; /* Отступ слева */ background-color: #ccc; /* Цвет фона */ padding: 10px; /* Поля вокруг текста */ > style> head> body> div class="layer1"> div class="layer2"> Коллективное бессознательное, как бы это ни казалось парадоксальным, многопланово продолжает невротический онтологический статус искусства. div> div> body> html>
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-left
Устанавливает величину отступа от левого края элемента. Отступом является расстояние от внешнего края левой границы текущего элемента до внутренней границы его родительского элемента (рис. 1).
Рис. 1. Отступ от левого края элемента
Синтаксис
margin-left: значение | auto | inherit
Значения
Величину левого отступа можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.
auto Указывает, что размер отступов будет автоматически рассчитан браузером. inherit Наследует значение родителя.
HTML5 CSS2.1 IE Cr Op Sa Fx
Результат данного примера показан на рис. 2.
Рис. 2. Применение свойства margin-left
Объектная модель
[window.]document.getElementById(» elementID «).style.marginLeftБраузеры
Браузер Internet Explorer 6 удваивает значение левого или правого отступа для плавающих элементов, вложенных в родительские элементы. Удваивается тот отступ, который прилегает к стороне родителя. Проблема обычно решается добавлением display: inline для плавающего элемента.
Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .