Свойство margin css
Содержание:
- Как узнать margin блока через браузер.
- CSS Tutorial
- Значения margin
- CSS Advanced
- Центрирование абсолютно позиционированных элементов
- Вопрос опять! — почему margin-bottom никак не сработал!?
- CSS Reference
- CSS Properties
- Syntax
- Свойство direction (строчная ось)
- Браузерная поддержка
- Проблемы с логическими свойствами
- Margin Collapse
- Example
- Свойство margin = «0»
- CSS Reference
- CSS Properties
- Центрирование и auto
Как узнать margin блока через браузер.
Иногда(вренее очень часто), если вы имеете дело к сайту. то вам рано или поздно придется смотреть на свой сайт в браузере, и в том числе вам потребуется увеличить или уменьшить margin, либо просто посмотреть значение свойства margin для данного блока!
Как его(margin) можно посмотреть в браузере!?
Нажимаем ПКМ по выбранному объекту, пусть это будет первый пункт в котором мы сейчас пишем.
В выпавшем окне ищем строчку — исследовать элемент(строка, в разных браузерах отличается, мы смотрим в яндекс браузере.).
Когда слева вы наводите наш блок, в данном случае «<li>», сверху он сразу выделяется цветом.
Если у данного блока есть свойства, то справа мы увидим их , в данном случае «margin-left: 30px;»
Если мы опустимся ниже, то увидим схему нашего блока, где также будем наблюдать margin слева.
Как узнать margin блока через браузер.
CSS Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS Z-indexCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !importantCSS Math Functions
Значения margin
В качестве значений margin используются любые допустимые единицы длины, к примеру, пиксели, проценты, em, rem и др. В отличие от padding свойство margin может быть отрицательным (например: -10px), а также принимать значение auto. В остальном margin похоже на padding, у него также может быть от одного до четырёх значений.
Одно значение — определяет отступы для всех сторон блока.
Два значения — первое определяет отступы сверху и снизу для элемента, второе слева и справа для элемента.
Три значения — первое задаёт отступ сверху для элемента, второе одновременно слева и справа, а третье снизу.
Четыре значения — первое определяет отступ сверху, второе справа, третье снизу, четвёртое слева. Для запоминания последовательности можно представить часы — значения идут по часовой стрелке, начиная с 12 часов.
Значение auto
Свойство margin позволяет выравнивать элемент по центру горизонтали, если использовать значение auto и задать ширину элемента через width (пример 1).
Пример 2. Значение auto
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>margin</title>
<style>
.dialog {
width: 80%; /* Ширина блока */
background: #D4E3A5; /* Цвет фона */
border: 2px solid #7D9B3D; /* Параметры рамки */
padding: 1rem; /* Поля */
margin: auto; /* Выравниваем по центру */
}
</style>
</head>
<body>
<div class=»dialog»>
Полинезийцы называют Млечный путь Манго-Роа-И-Ата,
что в переводе с маори означает «Длинная акула на рассвете».
</div>
</body>
</html>
Результат данного примера показан на рис. 3.
Рис. 3. Выравнивание блока по центру
Вместо margin: auto можно использовать комбинацию margin-left: auto и margin-right: auto.
Выравнивание блока по центру через значение auto работает только в сочетании с width.
Аналогично можно выровнять по центру горизонтали изображение, для этого даже не надо указывать ширину картинки, поскольку браузер получает её автоматически. Следует только превратить изображение в блочный элемент через свойство display, как показано в примере 3.
Пример 3. Значение auto
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>margin</title>
<style>
.center {
display: block; /* Блочный элемент */
margin: auto; /* Выравниваем по центру */
}
</style>
</head>
<body>
<img src=»image/html-128.png» alt=»HTML5″ class=»center»>
</body>
</html>
Результат данного примера показан на рис. 4.
Рис. 4. Выравнивание картинки по центру
Проценты
В качестве значения margin можно использовать процентную запись, с которой связаны следующие особенности.
- По горизонтали проценты считаются от ширины всего блока.
- По вертикали проценты считаются от ширины всего блока.
Таким образом, margin в процентах берётся от ширины всего блока, даже для margin-top и margin-botom.
Отрицательный margin
margin может быть задан с отрицательным значением, тем самым элемент сдвигается в противоположном направлении. К примеру, margin-top:-10px поднимает блок вверх на 10 пикселей, а margin-left:-10px сдвигает блок влево.
В примере 4 показан сдвиг блока с классом stat вверх, если он располагается сразу после элемента <p>.
Пример 4. Использование отрицательного значения
<!DOCTYPE html>
<html>
<head>
<meta charset=»utf-8″>
<title>margin</title>
<style>
p + .stat {
margin-top: -1rem; /* Поднимаем текст вверх */
}
.stat {
font-size: 3rem; /* Размер текста */
}
</style>
</head>
<body>
<p>Продано ёлок</p>
<p class=»stat»>64</p>
</body>
</html>
Результат данного примера показан на рис. 5. Без отрицательного margin строки располагаются далеко друг от друга.
Рис. 5. Поднимаем блок вверх через margin-top
CSS Advanced
CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
Conic Gradients
CSS Shadows
Shadow Effects
Box Shadow
CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS MaskingCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries
CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive
Центрирование абсолютно позиционированных элементов
Так как для абсолютно позиционированных элементов введено исключение, можно использовать значение 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.
Теперь, объединив все это, мы получим следующее:
Вопрос опять! — почему margin-bottom никак не сработал!?
Ответ точно такой же, что и в пункте 2.
НО!
В качестве бонуса : если к примеру вовнутрь блока поставим два наших блока без margin
<div style=»width: 100%; height: 200px; border: 1px solid black;»>
<div style=»width: 100px; height: 20px; border: 1px solid red; «>Наш блок.</div>
<div style=»width: 100px; height: 20px; border: 1px solid red; «>Наш блок №2.</div>
</div>
Получим:
Наш блок.
Наш блок.
Как видим…наши блоки прилепились друг к другу…
И если сейчас мы добавим к первому блоку margin-bottom: 20px;
<div style=»width: 100%; height: 200px; border: 1px solid black;»>
<div style=»width: 100px; height: 20px; border: 1px solid red; margin-bottom: 20px; «>Наш блок.</div>
<div style=»width: 100px; height: 20px; border: 1px solid red; «>Наш блок №2.</div>
</div>
То получим:
Наш блок.
Наш блок.
Какой вывод напрашивается!?
Что для того, чтобы margin-bottom и margin-right сработали, нужны определенные условия!
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Fallback FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight
gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
image-rendering
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
mask-image
mask-mode
mask-origin
mask-position
mask-repeat
mask-size
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
orphans
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-wrap
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
row-gap
scroll-behavior
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
widows
width
word-break
word-spacing
word-wrap
writing-mode
z-index
Syntax
The CSS margin property can be expressed with one, two, three or four values provided. And each value can be expressed as either a fixed value or as a percentage.
One Value
The syntax for the CSS margin property (with 1 value) is:
When one single value is provided, the margin value will apply to all four sides of the element (ie: top, right, bottom, left).
Two Values
The syntax for the CSS margin property (with 2 values) is:
When two values are provided, the first value will apply to the top and bottom of the element. The second value will apply to the left and right sides of the element.
Three Values
The syntax for the CSS margin property (with 3 values) is:
When three values are provided, the first value will apply to the top of the element. The second value will apply to the right and left sides of the element. The third value will apply to the bottom of the element.
Four Values
The syntax for the CSS margin property (with 4 values) is:
When four values are provided, the first value will apply to the top of the element. The second value will apply to the right side of the element. The third value will apply to the bottom of the element. The fourth value will apply to the left side of the element.
The top, right, bottom, and left margin values can be one of the following:
Свойство direction (строчная ось)
Определяет, откуда должен начинаться текст: слева направо или справа налево, но только в случае, если задано значение по умолчанию для свойства . Если мы поменяем значение на один из вертикальных режимов, то фактическое направление написания изменится с положения слева направо и будет идти сверху вниз. Или наоборот, при значении с (справа налево), оно изменится на сверху вниз.
Пример направления для арабского:
html { direction: rtl;}
Даже удивительно, на сколько просто сайт, идущий сверху вниз, можно преобразовать в идущий справа налево с горизонтальной прокруткой.
Я сделал небольшое демо. Его лучше смотреть в Firefox, в текущий момент именно в нём поддерживается наибольшее количество свойств.
Демо (попробуйте поменять язык):
Браузерная поддержка
- Все свойства блочной модели , , и новые свойства ширины и высоты (, ) уже работают во всех основных браузерах, кроме Edge.
- Новые значения для также работают везде, кроме Edge.
- Свойства и значения для , , работают пока только в Firefox.
Проблемы с логическими свойствами
Со всеми этими новыми доработками мы столкнёмся с новыми для нас проблемами. Например, что если мы захотим записать все значения свойства в сокращённом виде: ? В таком случае мы не сможем предсказать, как это будет проинтерпретировано браузером. Если сайт построен на физических свойствах, то значения будут расшифрованы следующим образом: , , , . Но если сайт построен на новых логических свойствах, то значения будут расшифрованы так: , , , .
На сайтах, написанных под английский (или русский) язык, физические и логические свойства будут работать одинаково. Для сайтов на других языках значения сокращений, как в примере с , должны работать в соответствии со значением свойства или .
Этот вопрос всё ещё открыт. Я внёс предложение, которое . Если у вас есть решение получше, то вы можете оставить комментарий в этой ветке!
В данный момент, если вы хотите использовать логические единицы, вам следует отказаться от шорткатов в пользу полных названий свойств.
Предложенное мною решение:
html { flow-mode: physical; /* или */ flow-mode: logical;}.box { /* будет интерпретироваться согласно значению flow-mode */ margin: 10px 5px 6px 3px; padding: 5px 10px 2px 7px;}
Margin Collapse
Top and bottom margins of elements are sometimes collapsed into a single
margin that is equal to the largest of the two margins.
This does not happen on horizontal (left and right) margins! Only vertical
(top and bottom) margins!
Look at the following example:
Example
p.a { margin: 30px 0;}p.b { margin: 20px 0;}
In the example above, the <p class=»a»> element has a top and bottom margin of 30px. The <p
class=»b»>
element has a top and bottom margin of 20px.
This means that the vertical margin between <p class=»a»> and <p class=»b»>
should be 50px (30px + 20px). But due to margin collapse, the actual margin ends
up being 30px!
Example
We will discuss the margin property below, exploring examples of how to use this property in CSS with 1, 2, 3, or 4 values (as either a fixed value or as a percentage).
Using Fixed Value
Let’s look at a CSS margin example where we provide one value expressed as a fixed value.
In this CSS margin example, we have provided one value of 10px which would apply to all 4 sides of the element.
Let’s look at how to use the optional auto value in the CSS margin property.
In this CSS margin example, we are centering the <div> tag and applying 0 margins.
Next, we’ll look at a CSS margin example where we provide two values expressed as a fixed value.
In this CSS margin example, we have provided two values. The first value of 10px would apply to the top and bottom of the element. The second value of 5em would apply to the left and right sides of the element.
Next, we’ll look at a CSS margin example where we provide three values expressed as a fixed value.
In this CSS margin example, we have provided three values. The first value of 2px would apply to the top of the element. The second value of 4px would apply to the right and left sides of the element. The third value of 6px would apply to the bottom of the element.
Next, we’ll look at a CSS margin example where we provide four values expressed as a fixed value.
In this CSS margin example, we have provided four values. The first value of 5px would apply to the top of the element. The second value of 10px would apply to the right side of the element. The third value of 12px would apply to the bottom of the element. The fourth value of 8px would apply to the left side of the element.
Using Percentage
Let’s look at a CSS margin example where we provide one value expressed as a percentage.
In this CSS margin example, we have provided one value of 4% which would apply to all 4 sides of the element.
Let’s look at how to use the optional auto value in the CSS margin property.
In this CSS margin example, we are centering the <div> tag and applying 4% margins.
Next, we’ll look at a CSS margin example where we provide two values expressed as a percentage.
In this CSS margin example, we have provided two values. The first value of 10% would apply to the top and bottom of the element. The second value of 5% would apply to the left and right sides of the element.
Next, we’ll look at a CSS margin example where we provide three values expressed as a percentage.
In this CSS margin example, we have provided three values. The first value of 2% would apply to the top of the element. The second value of 5% would apply to the right and left sides of the element. The third value of 10% would apply to the bottom of the element.
Next, we’ll look at a CSS margin example where we provide four values expressed as a percentage.
In this CSS margin example, we have provided four values. The first value of 5% would apply to the top of the element. The second value of 10% would apply to the right side of the element. The third value of 2% would apply to the bottom of the element. The fourth value of 8% would apply to the left side of the element.
Свойство margin = «0»
Начнем изучение margin, когда margin = «0» или вообще отсутствует!
Для этого нам понадобится какой-то блок на всю ширину нашей страницы, чтобы его увидеть добавим ему бордюр, установим высоту, ну к примеру, 300px.
width: 100%;
height: 200px;
border: 1px solid black;
И во внутрь поместим другой блок с текстом, что это наш блок.
width: 100px;
height: 20px;
border: 1px solid red;
И получим два блока, один внутри другого:
<div style=»width: 100%; height: 200px; border: 1px solid black;»>
<div style=»width: 100px; height: 20px; border: 1px solid red;»>Наш блок.</div>
</div>
Результат:
Наш блок.
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Fallback FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
font-weight
gap
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
image-rendering
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style-type
margin
margin-bottom
margin-left
margin-right
margin-top
mask-image
mask-mode
mask-origin
mask-position
mask-repeat
mask-size
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
orphans
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-wrap
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
row-gap
scroll-behavior
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
widows
width
word-break
word-spacing
word-wrap
writing-mode
z-index
Центрирование и auto
Каждое из свойств также может принимать значение . Значение в основном указывает браузеру определить поле за вас. В большинстве случаев значение auto будет эквивалентно значению 0 (которое является значением по умолчанию для каждого отступа). Тем не менее удобен для горизонтального центрирования:
Ниже показан пример такого центрирования.
See the Pen
margin auto by Андрей (@adlibi)
on CodePen.
В этом примере для центрирования блока по горизонтали в пределах доступного пространства выполняются две вещи:
- элементу задается ширина;
- Левое и правое поля устанавливаются в .
Без указанной ширины значения не имело бы никакого эффекта.
Также следует отметить, что полезен только для горизонтального центрирования, а его использование для верхнего и нижнего полей не центрирует элемент по вертикали, что может сбить с толку новичков.