Set a margin in html

margin

Свойство, которым можно отодвинуть элемент от соседей. Или придвинуть.

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Задаёт размер внешнего отступа вокруг элемента. Иногда внешние отступы называют полями.

Чтобы сделать отступ только с одной стороны, используй margin — top (сверху), margin — right (справа), margin — bottom (снизу) или margin — left (слева).

Или более современные margin — inline — start , margin — inline — end , margin — block — start и margin — block — end .

Примеры

Скопировать ссылку «Примеры» Скопировано

Применяется ко всем четырём сторонам:

 .selector  margin: 1em; margin: -3px;> .selector  margin: 1em; margin: -3px; >      

Сверху и снизу | слева и справа:

 .selector  margin: 5% auto;> .selector  margin: 5% auto; >      

Сверху | слева и справа | снизу:

 .selector  margin: 1em auto 2em;> .selector  margin: 1em auto 2em; >      

Сверху | справа | снизу | слева:

 .selector  margin: 2px 1em 0 auto;> .selector  margin: 2px 1em 0 auto; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

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

Отрицательное значение margin тоже возможно: вместо отступа, оно, наоборот, ставит элемент ближе к соседнему.

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

  • Если указать одно значение (например, margin : 1px; ), отступ в 1 пиксель появится со всех сторон;
  • Если указать два ( margin : 5 % auto; ), первое значение применится для верхнего и нижнего отступа, а второе для левого и правого;
  • При трёх значениях ( margin : 1em auto 2em; ) первое делает отступ сверху, второе — слева и справа, третье — снизу;
  • Если указать четыре значения ( margin : 2px 1em 0 auto; ), они применятся по часовой стрелке для каждой из сторон: сверху, справа, снизу и слева.

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Размер отступа margin можно задать в такими значениями:

Число с единицами измерения — фиксированный отступ в пикселях px или других единицах.

Проценты — отступ в процентах % от ширины блока.

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

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Свойство margin создаёт пространство вокруг элемента, в то время, как padding добавляет пространство внутри элемента.

💡 margin задаёт расстояние от края элемента до родительского элемента, а если такого нет, то до края окна браузера. По умолчанию браузерное окно имеет свои отступы внутри; чтобы от них избавиться, добавь в значение margin : 0 .

На практике

Скопировать ссылку «На практике» Скопировано

Дока Дог советует

Скопировать ссылку «Дока Дог советует» Скопировано

🛠 margin тот ещё непредсказуемый чёрт. Слева и справа работает адекватно, даже в строчных элементах. Но стоит сделать margin — top — так будь готов к сюрпризам. К примеру, все строчные элементы, то есть display : inline , вообще не учтут твой отступ сверху и снизу. Блочные тоже могут сработать, а могут и нет: в зависимости от родителя. Единственное, где в margin — top и margin — bottom можно быть уверенным — это в элементах с position : absolute и position : fixed — уж там margin точно не сможет тебя обмануть.

Егор Левченко советует

Скопировать ссылку «Егор Левченко советует» Скопировано

🛠 Чтобы упростить работу лучше всего использовать и padding (для внутренних отступов внутри блока) и margin для внешних отступов элемента внутри блока. Например, если у вас указаны корректные padding -отступы, то вам не придётся использовать margin — top для отступа от верхнего края для первого элемента.

После того, как вы задали внутренние отступы, всегда используйте один и тот же margin для вертикальных отступов. Отступ сверху из-за установленных внутренних padding -отступов у блока вам больше не нужен, поэтому пользуйтесь margin — bottom для отступов между элементами. Вы же пишете сверху вниз, правда? Тогда вам всегда будет понятно, почему тот или иной элемент находятся не там, где вам хочется.

Конечно, никто не запрещает использовать и популярное: margin : 0 auto; для центрирования элемента по строке.

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

🛠 Очень частый приём, который используется в вёрстке — выравнивание блочного элемента по центру родителя при помощи margin : 0 auto .

Предположим, есть основная колонка контента, которая должна находится по центру окна браузера. Для этого потребуется ограничить ширину колонки. Например, задать width : 80 % . Зачем? Потому что все блочные элементы по умолчанию имеют ширину 100%. Если не будет свободного места, то отцентрировать элемент не получится.

Теперь, когда у элемента появилось свободное место, можно применить к нему свойство margin : 0 auto . За счёт ключевого слова auto по бокам элемента будут равные внешние отступы, выравнивающие элемент по центру. В данном случае слева и справа отступ будет равен (100% — 80%) / 2 = 10%. Получается, размер, оставшийся после вычитания ширины элемента из 100%, делится на 2.

Причём боковые отступы будут гибкими. Если задать ширину элемента в пикселях, а затем выровнять при помощи margin — боковые отступы будут тянуться в зависимости от ширины окна браузера.

🛠 Начинающие разработчики часто злоупотребляют отрицательными отступами. Это очень плохая практика.

Представь, что ты делаешь перестановку в доме и решаешь поставить обеденный стол на 20 сантиметров над полом и на пол метра в стену. На сколько это будет логично и удобно?

Аналогично с элементами и отрицательными отступами. Если написан отрицательный отступ, то в 98% случаев это повод поискать ошибку в своей разметке или стилях.

Отрицательный отступ обоснован только если нужно разместить один элемент чуть-чуть поверх другого. В этом случае да, самый простой способ реализовать наложение — такой тип отступа. В другим случаях это просто поломка естественного потока документа 🤙🏼

Источник

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

        The margin CSS shorthand property sets the margin area on all four sides of an element.

        Try it

        Constituent properties

        This property is a shorthand for the following CSS properties:

        Syntax

        /* Apply to all four sides */ margin: 1em; margin: -3px; /* top and bottom | left and right */ margin: 5% auto; /* top | left and right | bottom */ margin: 1em auto 2em; /* top | right | bottom | left */ margin: 2px 1em 0 auto; /* Global values */ margin: inherit; margin: initial; margin: revert; margin: revert-layer; margin: unset; 

        The margin property may be specified using one, two, three, or four values. Each value is a , a , or the keyword auto . Negative values draw the element closer to its neighbors than it would be by default.

        • When one value is specified, it applies the same margin to all four sides.
        • When two values are specified, the first margin applies to the top and bottom, the second to the left and right.
        • When three values are specified, the first margin applies to the top, the second to the right and left, the third to the bottom.
        • When four values are specified, the margins apply to the top, right, bottom, and left in that order (clockwise).

        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 margin to use. For example, in certain cases this value can be used to center an element.

        Description

        This property can be used to set a margin on all four sides of an element. Margins create extra space around an element, unlike padding , which creates extra space within an element.

        The top and bottom margins have no effect on non-replaced inline elements, such as or .

        Horizontal centering

        To center something horizontally in modern browsers, you can use display : flex; justify-content : center; .

        However, in older browsers like IE8-9 that do not support Flexible Box Layout, these are not available. In order to center an element inside its parent, use margin: 0 auto; .

        Margin collapsing

        Elements’ top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins. See Mastering margin collapsing for more information.

        Formal definition

        • margin-bottom : 0
        • margin-left : 0
        • margin-right : 0
        • margin-top : 0
        • margin-bottom : the percentage as specified or the absolute length
        • margin-left : the percentage as specified or the absolute length
        • margin-right : the percentage as specified or the absolute length
        • margin-top : the percentage as specified or the absolute length

        Formal syntax

        Examples

        Simple example

        HTML

        div class="center">This element is centered.div> div class="outside">This element is positioned outside of its container.div> 

        CSS

        .center  margin: auto; background: lime; width: 66%; > .outside  margin: 3rem 0 0 -3rem; background: cyan; width: 66%; > 

        More examples

        margin: 5%; /* All sides: 5% margin */ margin: 10px; /* All sides: 10px margin */ margin: 1.6em 20px; /* top and bottom: 1.6em margin */ /* left and right: 20px margin */ margin: 10px 3% -1em; /* top: 10px margin */ /* left and right: 3% margin */ /* bottom: -1em margin */ margin: 10px 3px 30px 5px; /* top: 10px margin */ /* right: 3px margin */ /* bottom: 30px margin */ /* left: 5px margin */ margin: 2em auto; /* top and bottom: 2em margin */ /* Box is horizontally centered */ margin: auto; /* top and bottom: 0 margin */ /* Box is horizontally centered */ 

        Specifications

        Browser compatibility

        BCD tables only load in the browser

        See also

        • Introduction to the CSS basic box model
        • Margin collapsing
        • margin-top , margin-right , margin-bottom , and margin-left
        • 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.

        Источник

        Читайте также:  Php notice undefined index extension in
Оцените статью