- CSS Padding
- CSS Padding
- Padding — Individual Sides
- Example
- Padding — Shorthand Property
- Example
- Example
- Example
- Example
- Padding and Element Width
- Example
- Example
- More Examples
- All CSS Padding Properties
- CSS Padding
- CSS Padding
- Padding — Individual Sides
- Example
- Padding — Shorthand Property
- Example
- Example
- Example
- Example
- Padding and Element Width
- Example
- Example
- More Examples
- All CSS Padding Properties
- 5 способов создания ссылок-якорей с отступом сверху. Устранение смещения из-за фиксированного блока (шапка, меню).
- A: Стандартный якорь
- Б: Отступ в виде псевдоэлемента
- Замечания:
- В: Положительный padding и отрицательный margin
- Замечания:
- Г: Border и отрицательный margin
- Д: Метод Г с возможностью добавления border-top
- Смотрите также
- Миша
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:
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 aelement.
Set the right padding
This example demonstrates how to set the right padding of aelement.
Set the top padding
This example demonstrates how to set the top padding of aelement.
Set the bottom padding
This example demonstrates how to set the bottom padding of aelement.
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 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:
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 aelement.
Set the right padding
This example demonstrates how to set the right padding of aelement.
Set the top padding
This example demonstrates how to set the top padding of aelement.
Set the bottom padding
This example demonstrates how to set the bottom padding of aelement.
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 5 способов создания ссылок-якорей с отступом сверху. Устранение смещения из-за фиксированного блока (шапка, меню).
Впервые я столкнулся с этим, когда делал на своем сайте выплывающую панель «Поделиться в соц сетях» при скролле поста вниз (попробуйте).
При использовании ссылок-якорей на сайте, после перехода по ссылке, панель соц сетей закрывала верхнюю часть контента (как правило заголовок) и в итоге пользователю просто было непонятно, куда он в итоге попал. Вы можете опробовать это сами, кликнув по ссылке «A» ниже.
А так как сейчас очень популярно делать фиксированные шапки и меню position:fixed , прилепленные к верхней части экрана, то думаю что этот пост будет интересен многим. В нём я рассмотрю несколько вариантов якорей с отступами от верхней границы экрана при переходе по ним.
Для более ясного понимания на все h2 -заголовки я добавил заливку.
A: Стандартный якорь
Пример того, как работает стандартная ссылка-якорь. Если вы попали сюда, кликнув по ссылке, а не просто проскроллили страницу, то скорее всего заголовок у вас оказался полностью скрыт под панелью соц сетей.
Возможно было бы правильнее назвать пост не «5 методов…», а «4 метода…». Потому что это и не метод вовсе, а показательный пример того, как быть не должно, ну да ладно.
Б: Отступ в виде псевдоэлемента
Используем псевдоэлемент для добавления отступа перед элементом — :before или :after .
Поддержка браузерами: Chrome конечно же, IE8+, Firefox 3+, Opera 9.25+, Safari 3+.
Замечания:
- Требуется поддержка браузером CSS псеводоэлементов.
- Метод не работает корректно, если у элемента есть фон или заливка (наезжает на контент).
- Не работает корректно, если у элемента есть свойства padding-top или border-top .
#link-B:before { display: block; content: ""; height: 55px; margin: -55px 0 0; }
В: Положительный padding и отрицательный margin
Используем padding для создания отступа и отрицательный margin , чтобы этот же отступ убрать, а точнее — сделать его незаметным для пользователей.
Обратите внимание, что внутренные отступы padding тоже попадают под заливку, то есть, если у вашего элемента будет фон, то он скорее всего наедет на контент перед ним. Для того, чтобы игнорировать padding при добавлении фона на элемент, используйте CSS-свойство background-clip:content-box .
Поддержка браузерами: Chrome конечно же, Firefox 4.0+, Opera 10.6+, Safari 3+.
Замечания:
- Необходима поддержка браузером background-clip:content-box , но это только в том случае, если вы хотите добавить фон элементу.
- Некоторые ограничения при использовании margin (в том числе при margin-collapse — это когда из нижнего отступа первого элемента и верхнего отступа второго определяется наибольший, который и становится величиной отступа между этими элементами).
- Невозможность использования padding-top .
#link-C { padding-top: 55px; margin-top: -55px; -webkit-background-clip: content-box; background-clip: content-box; }
Г: Border и отрицательный margin
По сути то же самое, что и предыдущий метод, но вместо padding используем border . Что это нам даёт?
- Теперь вы спокойно можете использовать внутренние отступы padding .
- Постараюсь выразиться правильно — по идее border — это тот же padding , но только с заливкой и эффектами. Поэтому при использовании фона или заливки элемента нам нужно учесть, чтобы она распростаранялась на сам элемент и на padding , но не на border (ведь он то у нас прозрачный), здесь поможет background-clip:padding-box .
- Ограничение в использовании border-top , которое однако легко решаемо — смотрите ниже.
Поддержка браузерами: Chrome конечно же, Firefox 1.0+, Opera 10.5+, Safari 3+.
#link-D { border-top: 55px solid transparent; margin-top: -55px; padding: 15px; /* паддинги - без проблем */ -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; }
Д: Метод Г с возможностью добавления border-top
Дополнение к предыдущему методу, которое позволит добавить на элемент верхний border . Поддержка браузерами псевдоэлементов и background-clip (только при наличии фона или заливки) обязательна.
Поддержка браузерами: Chrome конечно же, Firefox 3.5+, Opera 10.5+, Safari 3+.
#link-E { position: relative; /* важно - для того, чтобы псевдоэлемент позиционировался относительно этого элемента */ border-top: 55px solid transparent; margin-top: -55px; -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box; } #link-E:before { content: ""; position: absolute; top: -2px; /* равен по модулю толщине border */ left: 0; right: 0; border-top: 2px solid #ccc; /* собственно то, ради чего всё затевалось */ }
Смотрите также
Миша
Впервые познакомился с WordPress в 2009 году. Организатор и спикер на конференциях WordCamp. Преподаватель в школе Нетология.
Пишите, если нужна помощь с сайтом или разработка с нуля.