margin-top

CSS margin-top Property

The margin-top property is used to define the top margin of an element.

The top and bottom margins of an element can collapse into one, which is equal to the largest of the two margins. However, this happens only in the case of vertical margins.

Initial Value 0
Applies to All elements. It also applies to ::first-letter.
Inherited No.
Animatable Yes. Top margin of the element is animatable.
Version CSS2
DOM Syntax object.style.marginTop = «50px»;

Syntax

margin-top: length | auto | initial | inherit;

Example of the margin-top property:

html> html> head> title>Title of the document title> style> .margin-top < margin-top: 100px; > style> head> body> h2>Margin-top property example h2> p>No specified margin. p> p class="margin-top"> 100px margin is specified top for this text. p> body> html>

Result

CSS margin-top Property

Example of the margin-top property specified in «em»:

html> html> head> title>Title of the document title> style> p.example < margin-top: 5em; > style> head> body> h2>Margin-top property example h2> p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> p class="example">Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. p> body> html>

Example of the margin-top property specified in «%»:

html> html> head> title>Title of the document title> style> .margin-top < margin-top: 10%; background-color: lightblue; > style> head> body> h2>Margin-top property example h2> p>No specified margin. p> p class="margin-top"> 10% margin is specified top for this text. p> body> html>

Example of the margin-top property with the «initial» value:

html> html> head> title>Title of the document title> style> .margin-top < margin-top: initial; background-color: lightgreen; > style> head> body> h2>Margin-top property example h2> p>No specified margin. p> p class="margin-top"> Margin top is specified for this text. p> body> html>

Example of the margin-top property with the «inherit» value:

html> html> head> title>Title of the document title> style> div < margin-top: 50px; > .margin-top < margin-top: inherit; background-color: lime; > style> head> body> h2>Margin-top property example h2> div> Here is some text. p class="margin-top"> Margin top is specified for this text. p> div> body> html>

Values

Value Description Play it
auto Sets the top margin. It is the default value of this property. Play it »
length Defines a top margin in px, pt, cm, etc. Default value is 0. Play it »
% Sets the top 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.
Читайте также:  Python list get elements by index

Browser support

Источник

margin-top

Устанавливает величину отступа от верхнего края элемента. Отступом является расстояние от внешнего края верхней границы текущего элемента до внутренней границы его родительского элемента (рис. 1).

Отступ от верхнего края элемента

Рис. 1. Отступ от верхнего края элемента

Краткая информация

Синтаксис

Синтаксис

Описание Пример
Указывает тип значения.
A && B Значения должны выводиться в указанном порядке. &&
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
[ ] Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,]*
+ Повторять один или больше раз. +
? Указанный тип, слово или группа не является обязательным. inset?
Повторять не менее A, но не более B раз.
# Повторять один или больше раз через запятую. #

Значения

Величину верхнего отступа можно указывать в пикселях (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.

auto Указывает, что размер отступов будет автоматически рассчитан браузером.

Песочница

Винни-Пух был всегда не прочь немного подкрепиться, в особенности часов в одиннадцать утра, потому что в это время завтрак уже давно окончился, а обед ещё и не думал начинаться. И, конечно, он страшно обрадовался, увидев, что Кролик достаёт чашки и тарелки.

Пример

Результат данного примера показан на рис. 2.

Применение свойства margin-top

Рис. 2. Применение свойства margin-top

Объектная модель

Объект.style.marginTop

Примечание

Браузер Internet Explorer до версии 7 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

Спецификация

Спецификация Статус
CSS Basic Box Model Рабочий проект
CSS Transitions Рабочий проект
CSS Level 2 (Revision 1) Рекомендация
CSS Level 1 Рекомендация

Спецификация

Каждая спецификация проходит несколько стадий одобрения.

  • Recommendation ( Рекомендация ) — спецификация одобрена W3C и рекомендована как стандарт.
  • Candidate Recommendation ( Возможная рекомендация ) — группа, отвечающая за стандарт, удовлетворена, как он соответствует своим целям, но требуется помощь сообщества разработчиков по реализации стандарта.
  • Proposed Recommendation ( Предлагаемая рекомендация ) — на этом этапе документ представлен на рассмотрение Консультативного совета W3C для окончательного утверждения.
  • Working Draft ( Рабочий проект ) — более зрелая версия черновика после обсуждения и внесения поправок для рассмотрения сообществом.
  • Editor’s draft ( Редакторский черновик ) — черновая версия стандарта после внесения правок редакторами проекта.
  • Draft ( Черновик спецификации ) — первая черновая версия стандарта.

Браузеры

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

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

Число указывает версию браузреа, начиная с которой элемент поддерживается.

См. также

Справочник CSS

  • !important
  • ::after
  • ::backdrop
  • ::before
  • ::first-letter
  • ::first-line
  • ::placeholder
  • ::selection
  • :active
  • :blank
  • :checked
  • :default
  • :disabled
  • :empty
  • :enabled
  • :first-child
  • :first-of-type
  • :focus
  • :focus-within
  • :fullscreen
  • :hover
  • :in-range
  • :indeterminate
  • :invalid
  • :lang
  • :last-child
  • :last-of-type
  • :link
  • :not
  • :nth-child
  • :nth-last-child
  • :nth-last-of-type
  • :nth-of-type
  • :only-child
  • :only-of-type
  • :optional
  • :out-of-range
  • :placeholder-shown
  • :read-only
  • :read-write
  • :required
  • :root
  • :target
  • :valid
  • :visited
  • @charset
  • @document
  • @font-face
  • @import
  • @keyframes
  • @media
  • @page
  • @supports
  • @viewport
  • 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
  • backdrop-filter
  • backface-visibility
  • background
  • background-attachment
  • background-blend-mode
  • background-clip
  • background-color
  • background-image
  • background-origin
  • background-position
  • background-position-x
  • background-position-y
  • background-repeat
  • background-size
  • block-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-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
  • caption-side
  • caret-color
  • clear
  • clip
  • 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-family
  • font-kerning
  • font-size
  • font-stretch
  • font-style
  • font-variant
  • font-weight
  • height
  • hyphens
  • image-rendering
  • justify-content
  • left
  • letter-spacing
  • line-clamp
  • line-height
  • list-style
  • list-style-image
  • list-style-position
  • list-style-type
  • margin
  • margin-bottom
  • margin-left
  • margin-right
  • margin-top
  • marks
  • max-height
  • max-width
  • min-height
  • min-width
  • mix-blend-mode
  • object-fit
  • opacity
  • order
  • orphans
  • outline
  • outline-color
  • outline-offset
  • outline-style
  • outline-width
  • overflow
  • overflow-x
  • overflow-y
  • padding
  • padding-block
  • padding-block-end
  • padding-block-start
  • padding-bottom
  • padding-inline
  • padding-inline-end
  • padding-inline-start
  • padding-left
  • padding-right
  • padding-top
  • page-break-after
  • page-break-before
  • page-break-inside
  • perspective
  • perspective-origin
  • place-content
  • pointer-events
  • position
  • quotes
  • resize
  • right
  • scroll-behavior
  • tab-size
  • table-layout
  • text-align
  • text-align-last
  • text-decoration
  • text-decoration-color
  • text-decoration-line
  • text-decoration-skip-ink
  • text-decoration-style
  • text-emphasis
  • text-emphasis-color
  • text-emphasis-position
  • text-emphasis-style
  • text-fill-color
  • text-indent
  • text-orientation
  • text-overflow
  • text-shadow
  • text-stroke
  • text-stroke-color
  • text-stroke-width
  • 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
  • zoom

Источник

margin-top

Устанавливает величину отступа от верхнего края элемента. Отступом является расстояние от внешнего края верхней границы текущего элемента до внутренней границы его родительского элемента (рис. 1).

Рис. 1. Отступ от верхнего края элемента

Рис. 1. Отступ от верхнего края элемента

Синтаксис

margin-top: значение | auto | inherit

Значения

Величину верхнего отступа можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.

auto Указывает, что размер отступов будет автоматически рассчитан браузером. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

        
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 2.

Применение свойства margin-top

Рис. 2. Применение свойства margin-top

Объектная модель

[window.]document.getElementById(» elementID «).style.marginTop

Браузеры

Браузер Internet Explorer 6 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

margin-top

Устанавливает величину отступа от верхнего края элемента. Отступом является расстояние от внешнего края верхней границы текущего элемента до внутренней границы его родительского элемента (рис. 1).

Рис. 1. Отступ от верхнего края элемента

Рис. 1. Отступ от верхнего края элемента

Синтаксис

margin-top: значение | auto | inherit

Значения

Величину верхнего отступа можно указывать в пикселах (px), процентах (%) или других допустимых для CSS единицах. Значение может быть как положительным, так и отрицательным числом.

auto Указывает, что размер отступов будет автоматически рассчитан браузером. inherit Наследует значение родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

        
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diem nonummy nibh euismod tincidunt ut lacreet dolore magna aliguam erat volutpat. Ut wisis enim ad minim veniam, quis nostrud exerci tution ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.

Результат данного примера показан на рис. 2.

Применение свойства margin-top

Рис. 2. Применение свойства margin-top

Объектная модель

[window.]document.getElementById(» elementID «).style.marginTop

Браузеры

Браузер Internet Explorer 6 в некоторых случаях некорректно вычисляет значение отступа, заданное в процентах.

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit .

Источник

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