margin-top

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-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

        The margin-top CSS property sets the margin area on the top of an element. A positive value places it farther from its neighbors, while a negative value places it closer.

        Try it

        This property has no effect on non-replaced inline elements, such as or .

        Syntax

        /* values */ margin-top: 10px; /* An absolute length */ margin-top: 1em; /* relative to the text size */ margin-top: 5%; /* relative to the nearest block container's width */ /* Keyword values */ margin-top: auto; /* Global values */ margin-top: inherit; margin-top: initial; margin-top: revert; margin-top: revert-layer; margin-top: unset; 

        The margin-top 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 browser selects a suitable value to use. See margin .

        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

        Examples

        Setting positive and negative top margins

        .content  margin-top: 5%; > .sidebox  margin-top: 10px; > .logo  margin-top: -5px; > #footer  margin-top: 1em; > 

        Specifications

        Browser compatibility

        BCD tables only load in the browser

        See also

        • margin-right , margin-bottom , and margin-left and the margin shorthand
        • The mapped logical properties: margin-block-start , margin-block-end , margin-inline-start , and margin-inline-end and the shorthands margin-block and margin-inline

        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.

        Источник

        margin-top¶

        Свойство margin-top устанавливает величину отступа от верхнего края элемента.

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

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

        Демо¶

        Синтаксис¶

         1 2 3 4 5 6 7 8 9 10 11 12
        /* values */ margin-top: 10px; /* An absolute length */ margin-top: 1em; /* relative to the text size */ margin-top: 5%; /* relative to the nearest block container's width */ /* Keyword values */ margin-top: auto; /* Global values */ margin-top: inherit; margin-top: initial; margin-top: 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
         html> head> meta charset="utf-8" /> title>margin-toptitle> style> div  background: #fc3; /* Цвет фона */ border: 2px solid black; /* Параметры рамки */ padding: 20px; /* Поля вокруг текста */ margin-top: 20%; /* Отступ сверху */ > style> head> body> div> Весьма существенно следующее: аллегория монотонно иллюстрирует невротический холерик, таким образом, второй комплекс движущих сил получил разработку в трудах А.Берталанфи и Ш.Бюлера. div> body> html> 

        Источник

        Div style margin top html

        Свойство margin определяет отступ элемента от других элементов или границы внешнего контейнера. Существуют специальные свойства CSS для задания отступов для каждой стороны:

        • margin-top : отступ сверху
        • margin-bottom : отступ снизу
        • margin-left : отступ слева
        • margin-right : отступ справа
                

        Первый блок

        Второй блок

        Третий блок

        Margin в CSS 3

        Можно вместо четырех свойств задать одно:

        Свойство задается в формате:

        margin: отступ_сверху отступ_справа отступ_снизу отступ_слева;

        Если значения для всех четырех отступов совпадает, то мы можем указать только одно значение:

        В этом случае для всех четырех отступов будет использоваться 25 пикселей.

        Для установки отступов можно использовать точные значения в пикселях (px) или em, либо процентные отношения, либо значение auto (автоматическая установка отступов).

        Значение 2 em определяет расстояние, которое в два раза больше размера шрифта элемента.

        При использовании процентов веб-браузеры вычисляют размер отступов на основе ширины элемента-контейнера, в который заключен стилизуемый элемент.

        В то же время, если несколько элементов у нас соприкасаются, то браузер выбирает наибольший отступ элемента, который затем и используется. Так, выше в примере использовался следующий стиль:

        Между первым и вторым блоками расстояние будет равно 30 пикселям — значение свойства margin-top второго блока div, несмотря на то, что у первого блока div имеется свойство margin-bottom , равное 15 пикселям.

        Источник

        Читайте также:  Python set minus set
Оцените статью