padding

CSS Padding

The CSS padding property is used for creating space around the content of an element. CSS provides different properties, with the help of which you can set the padding for an element’s each side (right, left, top and bottom).

The individual sides

With the help of the following properties you can set the padding for each side of an element:

As you can guess, for the top, we use padding-top, for bottom padding-bottom, for left side padding-left and right padding-right.

All the padding properties can have the values below:

  • length, which is used for specifying a padding in px, pt, cm, etc,
  • %, which specifies a padding in % of the width of the containing element,
  • inherit , which specifies that the padding must be inherited from its parent element.

Take into account, that CSS padding property cannot accept negative values. Its default value for all padding properties is 0.

Example of the individual padding properties:

html> html> head> title>Title of the document title> style> div < background-color: yellow; padding-top: 50px; padding-right: 30px; padding-bottom: 50px; padding-left: 80px; > style> head> body> h2>Individual padding properties h2> div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.. div> body> html>

Padding as a shorthand property

The CSS padding property is a shorthand property for the individual padding properties below:

In the cases, when the padding property has only 1 value, for example padding: 35px, all the four paddings are 35px.

Example of the padding shorthand property with one value:

html> html> head> title>Title of the document title> style> div < background-color: green; padding: 35px; > style> head> body> h2>Individual padding properties h2> div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. div> body> html>

The padding property may have 2 values, for example padding: 20px 40px, where top and bottom paddings are 20px, right and left paddings are 40px.

This is the same with the code above.

p < padding-top: 20px; padding-right: 40px; padding-bottom: 20px; padding-left: 40px; >

Example of the padding shorthand property with two values:

html> html> head> title>Title of the document title> style> p < background-color: #1c87c9; color: white; padding: 20px 40px; > style> head> body> p>Paragraph with background-color, color and padding properties. p> body> html>

Result

CSS Padding Property

The padding property may have 3 values, for example, padding: 20px 15px 35px;, where top padding is 20px, right and left paddings are 15px and bottom padding is 35px.

Читайте также:  Html link href media

This is the same with the code above.

p < padding-top: 20px; padding-right: 15px; padding-bottom: 35px; padding-left: 15px; >

Example of the padding shorthand property with three values:

html> html> head> title>Title of the document title> style> div < background-color: lightblue; padding: 20px 15px 35px; > style> head> body> h2>Example of the padding shorthand property h2> div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. div> body> html>

And finally, the padding property can have four values, for example padding: 25px 50px 75px 100px;, where top padding is 25px, right padding is 50px, bottom padding is 75px and left padding is 100px.

p < padding: 25px 50px 75px 100px; >

Example of the padding shorthand property with four values:

html> html> head> title>Title of the document title> style> div < background-color: #95e5f7; padding: 25px 50px 75px 100px; > style> head> body> h2>Example of the padding shorthand property h2> div> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. div> body> html>

Browser support

Practice Your Knowledge

padding: 20px 40px 20px 40px is the same with the code above

padding-top: 20px; padding-left: 40px; padding-right: 20px; padding-bottom: 40px; padding-top: 20px; padding-bottom: 40px; padding-right: 20px; padding-left: 40px; padding-bottom: 20px; padding-left: 40px; padding-top: 20px; padding-right: 40px;

Источник

padding

Свойство padding устанавливает внутренние отступы/поля со всех сторон элемента. Область отступов это пространство между содержанием элемента и его границей. Отрицательные значения не допускаются.

Свойство padding краткая форма записи свойств, чтобы не писать отдельное правило для каждой стороны ( padding-top , padding-right , padding-bottom , padding-left ).

  • padding-bottom (en-US): 0
  • padding-left : 0
  • padding-right : 0
  • padding-top (en-US): 0
  • padding-bottom (en-US): процент, как указан, или абсолютная длина
  • padding-left : процент, как указан, или абсолютная длина
  • padding-right : процент, как указан, или абсолютная длина
  • padding-top (en-US): процент, как указан, или абсолютная длина

Синтаксис

/* Применяется для всех 4 сторон */ padding: 1em; /* По вертикали | По горизонтали */ padding: 5% 10%; /* Сверху | По горизонтали | Снизу */ padding: 1em 2em 2em; /* Сверху | Справа | Снизу | Слева */ padding: 2px 1em 0 1em; /* Глобальные значения */ padding: inherit; padding: initial; padding: unset; 

Значения

Укажите одно, два, три или четыре следующих значения:

Устанавливает неотрицательный, фиксированный размер. Подробнее в разделе .

Относительно ширины родительского блока.

Источник

CSS Padding

Padding is used to create space around an element’s content, inside of any defined borders.

CSS Padding

The CSS padding properties are used to generate space around an element’s content, inside of any defined borders.

With CSS, you have full control over the padding. There are properties for setting the padding for each side of an element (top, right, bottom, and left).

Padding — Individual Sides

CSS has properties for specifying the padding for each side of an element:

Читайте также:  Adjusted rand index python

All the padding properties can have the following values:

  • length — specifies a padding in px, pt, cm, etc.
  • % — specifies a padding in % of the width of the containing element
  • inherit — specifies that the padding should be inherited from the parent element

Note: Negative values are not allowed.

Example

Set different padding for all four sides of a element:

Padding — Shorthand Property

To shorten the code, it is possible to specify all the padding properties in one property.

The padding property is a shorthand property for the following individual padding properties:

If the padding property has four values:

  • padding: 25px 50px 75px 100px;
    • top padding is 25px
    • right padding is 50px
    • bottom padding is 75px
    • left padding is 100px

    Example

    Use the padding shorthand property with four values:

    If the padding property has three values:

    • padding: 25px 50px 75px;
      • top padding is 25px
      • right and left paddings are 50px
      • bottom padding is 75px

      Example

      Use the padding shorthand property with three values:

      If the padding property has two values:

      • padding: 25px 50px;
        • top and bottom paddings are 25px
        • right and left paddings are 50px

        Example

        Use the padding shorthand property with two values:

        If the padding property has one value:

        Example

        Use the padding shorthand property with one value:

        Padding and Element Width

        The CSS width property specifies the width of the element’s content area. The content area is the portion inside the padding, border, and margin of an element (the box model).

        So, if an element has a specified width, the padding added to that element will be added to the total width of the element. This is often an undesirable result.

        Example

        Here, the element is given a width of 300px. However, the actual width of the element will be 350px (300px + 25px of left padding + 25px of right padding):

        To keep the width at 300px, no matter the amount of padding, you can use the box-sizing property. This causes the element to maintain its actual width; if you increase the padding, the available content space will decrease.

        Example

        Use the box-sizing property to keep the width at 300px, no matter the amount of padding:

        More Examples

        Set the left padding
        This example demonstrates how to set the left padding of a

        element.

        Set the right padding
        This example demonstrates how to set the right padding of a

        element.

        Set the top padding
        This example demonstrates how to set the top padding of a

        element.

        Set the bottom padding
        This example demonstrates how to set the bottom padding of a

        element.

        All CSS Padding Properties

        Property Description
        padding A shorthand property for setting all the padding properties in one declaration
        padding-bottom Sets the bottom padding of an element
        padding-left Sets the left padding of an element
        padding-right Sets the right padding of an element
        padding-top Sets the top padding of an element

        Источник

        Свойство padding

        Свойство padding задаёт расстояние от внутреннего края границы или края блока до воображаемого прямоугольника, ограничивающего содержимое блока (рис. 1).

        padding

        Основное предназначение padding — создать пустое пространство вокруг содержимого элемента, например текста, чтобы он не прилегал плотно к краю элемента. Использование padding повышает читабельность текста и улучшает внешний вид страницы. В примере 1 показано применение padding для оформления текста.

        Пример 1. Использование padding

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

        Поля вокруг текста

        Ячейки таблицы

        Значения padding

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

        Одно значение — определяет поля для всех сторон блока.

        padding: все стороны; padding: 10px;

        Два значения — первое определяет поля сверху и снизу для элемента, второе слева и справа для элемента.

        padding: верх-низ лево-право; padding: 10px 20px;

        Три значения — первое задаёт поле сверху для элемента, второе одновременно слева и справа, а третье снизу.

        padding: верх лево-право низ; padding: 10px 20px 5px;

        Четыре значения — первое определяет поле сверху, второе справа, третье снизу, четвёртое слева. Для запоминания последовательности можно представить часы — значения идут по часовой стрелке, начиная с 12 часов.

        padding: верх право низ лево; padding: 5px 10px 15px 20px;

        В качестве единиц обычно используются пиксели, em, rem и др.

        padding не допускает отрицательного значения, если вы указали его по ошибке, оно будет проигнорировано.

        Проценты

        В качестве значения padding можно использовать процентную запись, с которой связаны некоторые хитрости.

        • По горизонтали проценты считаются от ширины всего блока.
        • По вертикали проценты считаются от ширины всего блока.

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

        Проценты можно сочетать с фиксированными значениями, получится что-то вроде этого.

        Сопутствующие свойства

        Наряду с padding используются свойства padding-top, padding-right, padding-bottom, padding-left, которые, соответственно, задают значения сверху, справа, снизу и слева. Эти свойства применяются, когда требуется задать поле с одной-двух сторон или когда не следует затрагивать уже выставленное значение padding . В примере 2 показано создание маркированного списка. Расстояние от маркера до текста меняется с помощью свойства padding-left .

        Пример 2. Маркированный список

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

        Список

        Цвет фона

        Свойство padding определяет пространство от границ до содержимого блока и это пространство заполняется фоновым цветом, заданным для всего блока. Данную особенность можно использовать для создания различных рамок. Так, если установить для фоновый цвет, то он не будет виден, поскольку картинка его закрывает. Но если добавить padding , то фон расширится и тем самым мы получим одноцветную рамку вокруг изображения. Комбинируя padding и border можно создавать разные рамки, как показано в примере 3.

        Пример 3. Рамка вокруг изображения

        padding padding

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

        Рамка, созданная с помощью padding

        Рис. 4. Рамка, созданная с помощью padding

        Учтите, что этот способ подходит для изображений без прозрачных участков, иначе через «дыры» будет виден фоновый цвет.

        Аналогичным образом делаются рамки и для блоков, но внутрь блока следует добавить , для которого ставится фоновый цвет. Тем самым можно получить не только одноцветные рамки, но и градиентные, как показано в примере 4.

        Пример 4. Градиентная рамка

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

        Градиентная рамка, созданная с помощью padding

        Рис. 5. Градиентная рамка, созданная с помощью padding

        Источник

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