Margin

Содержание:

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Frequently Asked Questions

What does it mean to trade on margin?

Trading on margin means borrowing money from a brokerage firm in order to carry out trades. When trading on margin, investors first deposit cash that then serves as collateral for the loan, and then pay ongoing interest payments on the money they borrow. This loan increases the buying power of investors, allowing them to buy a larger quantity of securities. The securities purchased automatically serve as collateral for the margin loan.

What is a margin call?

A margin call is a scenario in which a broker who had previously extended a margin loan to an investor sends a notice to that investor asking them to increase the amount of collateral in their margin account. When faced with a margin call, investors often need to deposit additional cash into their account, sometimes by selling other securities. If the investor refuses to do so, the broker has the right to forcefully sell the investor’s positions in order to raise the necessary funds. Many investors fear margin calls because they can force investors to sell positions at unfavorable prices.

What are some other meanings of the term margin?

Outside of margin lending, the term margin also has other uses in finance. For example, it is used as a catch-all term to refer to various profit margins, such as the gross profit margin, pre-tax profit margin, and net profit margin. The term is also sometimes used to refer to interest rates or risk premiums.

Значения 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

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Margin Shorthand Property

The Box Model below indicates how separate parts of a box interact with each other. This model in CSS consists of several components: the content, padding, border, and margin.

CSS margins have four parts:

With the shorthand, you can set all the properties above in one declaration.

Margin vs Padding

  • Both margins and padding belong to the Box Model.
  • The main difference is that adds space around an element, while creates a space within an element.
  • You cannot use value to make browsers automatically set .
  • vs discussion occurs because these components are similar, but their use cases differ.

    • separates elements from other blocks outside the element.
    • shifts content inside elements further from the edges.

Setting One or Multiple Values

The margins in CSS can have one, two, three, or four values:

  • One value uses the same margin to all sides.
  • Two values: the first margin sets the top and bottom. The second sets the left and right sides.
  • Three values: the first sets the top. The second sets the left and right. The third sets the bottom.
  • Four values: order of values goes like this — top, right, bottom, and left.

Example Copy

I have margins!

The example above has all four values: . CSS assigns them to the element like this:

  • Top margin size is 10px
  • Right margin size is 20px
  • Bottom margin size is 30px
  • Left margin size is 70px

In the example below, we have three values: . We will get these results:

Example Copy

I have margins!

  • Top margin size is 10px
  • Right and left margin size is 20px
  • Bottom margin size is 30px

The following example assigns two values: to the element:

Example Copy

I have margins!

  • Top and bottom margin size is 10px each
  • Right and left margin size is 20px each

To set all four margins the same, you only need to specify one value:

Example Copy

I have margins!

The example below illustrates individual margins with values specified in pixels.

I have margins!

Example Copy

Свойства margin и padding на примере сайта

Рассмотрим свойства на примерах с элементами. Мы начнем с абзаца (тега <p>), затем добавим к нему цвет фона и добавим отступ 30px с каждой стороны.

Ниже слева видно, что это абзац с padding 30px вокруг него. На изображении справа я использовал инструменты Google Chrome, чтобы показать, где padding HTML начинается /заканчивается для этого элемента. Зеленый цвет на изображении ниже – это padding, который расположен вокруг контейнера. Темно-синий цвет фона заполняет внутреннюю область:

Теперь добавим margin абзацу. Я добавлю отступ сверху и снизу 30px, а также 20px слева и справа. Ниже на изображении слева показано, как этот абзац изменился с margin. Фактическая ширина изображения стала меньше, потому что margin отталкивает от границ другой HTML элемент. Справа видно, что оранжевый цвет – это margin вокруг элемента. margin всегда находится за пределами padding и темно-синий фон не распространяется на область margin:

Если вы до сих пор путаетесь, как использовать margin и padding, то пришло время экспериментировать! Чем больше вы будете использовать свойства CSS, и изменять их значения, тем лучше поймете, как они работают.

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

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS 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
@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
max-height
max-width
@media
min-height
min-width
mix-blend-mode

object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
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
width
word-break
word-spacing
word-wrap
writing-mode

z-index

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

Так как для абсолютно позиционированных элементов введено исключение, можно использовать значение 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

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

Для иллюстрации возьмем следующий HTML-код:

И следующий CSS:

В этом примере для элемента задано нижнее поле в 20 пикселей. Элемент абзаца, который следует сразу за ним, имеет верхнее поле, равное 10 пикселям.

Казалось бы, что величина вертикального поля между и абзацем будет в общей сложности 30 пикселей (20 пикселей + 10 пикселей). Но из-за коллапса полей фактически она окажется всего 20 пикселей. Это показано на примере ниже:

See the Pen
схлопывание margin by Андрей (@adlibi)
on CodePen.

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

Кроме того, это позволяет использовать более последовательный подход к объявлению универсальных полей для элементов страницы. Например, заголовки обычно имеют вертикальные поля, как и абзацы. Если бы поля не сжимались, заголовки, следующие за абзацами (или наоборот), часто требовали бы изменения полей применительно к одному из элементов, чтобы добиться равных отступов по вертикали.

Схлопывание полей также применяется к вложенным элементам. Посмотрите следующий пример:

See the Pen
схлопывание внутренних margin by Андрей (@adlibi)
on CodePen.

Здесь абзац имеет верхнее поле в 30 пикселей, который вложен в элемент с верхним полем 40 пикселей. Кроме того, у заголовка нижнее поле 20 пикселей.

Опять же, здравый смысл подсказывает, что общее пространство вертикальных полей здесь будет составлять 90 пикселей (20 + 40  + 30), но вместо этого все поля сворачиваются в одно поле в 40 пикселей (самое большое из трех). Это полезно в большинстве случаев, поскольку нет необходимости переопределять какие-либо из верхних полей, чтобы убрать лишнее вертикальное пространство.

Изменения, которые нужно учесть

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

  • заменить на
  • заменить на

Но, похоже, пока не стоит этого ждать, по крайней мере в отношении . Это свойство обновили буквально только что и в его названии по-прежнему присутствует . Пример: .

Но кто знает, может этот пост попадётся на глаза правильным людям из W3C 🙂

Резюмируя

Вот и всё. Я надеюсь, что вам понравилась эта статья и вы узнали что-то новое. Я буду признателен, если вы поаплодируете или поделитесь этим постом 🙂

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *