- CSS box-shadow Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- box-shadow
- Интерактивный пример
- Синтаксис
- Значения
- Интерполяция
- Формальное определение
- Формальный синтаксис
- Примеры
- Добавление трёх теней
- HTML
- CSS
- Результат
- Использование нулевых значений для смещений и радиуса размытия
- HTML
- How to Set a Box-Shadow Only on the Left and Right Sides
- Example of adding a box-shadow on the left and right sides with the :before and :after pseudo-elements:
- Result
- Example of adding a box-shadow on the left and right sides:
- Example of setting a box-shadow on the left and right sides without any shadow on top and bottom:
- How to Set a Box-Shadow on One Side of the Element
- Create HTML
- Add CSS
- Example of adding a box-shadow on the left side of the element:
- Result
- Example of adding a box-shadow on the bottom of the element:
- Example of adding a box-shadow inside the element:
- Example of adding outside and inside shadows:
CSS box-shadow Property
The box-shadow property attaches one or more shadows to an element.
Default value: | none |
---|---|
Inherited: | no |
Animatable: | yes. Read about animatable Try it |
Version: | CSS3 |
JavaScript syntax: | object.style.boxShadow=»10px 20px 30px blue» Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
Numbers followed by -webkit- or -moz- specify the first version that worked with a prefix.
CSS Syntax
Note: To attach more than one shadow to an element, add a comma-separated list of shadows (see «Try it Yourself» example below).
Property Values
Value | Description | Demo |
---|---|---|
none | Default value. No shadow is displayed | Demo ❯ |
h-offset | Required. The horizontal offset of the shadow. A positive value puts the shadow on the right side of the box, a negative value puts the shadow on the left side of the box | Demo ❯ |
v-offset | Required. The vertical offset of the shadow. A positive value puts the shadow below the box, a negative value puts the shadow above the box | Demo ❯ |
blur | Optional. The blur radius. The higher the number, the more blurred the shadow will be | Demo ❯ |
spread | Optional. The spread radius. A positive value increases the size of the shadow, a negative value decreases the size of the shadow | Demo ❯ |
color | Optional. The color of the shadow. The default value is the text color. Look at CSS Color Values for a complete list of possible color values. |
More Examples
Example
Add a blur effect to the shadow:
box-shadow
CSS-свойство box-shadow добавляет тень к элементу. Через запятую можно задать несколько теней. Тень описывается смещениями по оси X и Y относительно элемента, радиусом размытия и распространения, а также цветом.
Интерактивный пример
Свойство box-shadow включает отбрасывание тени от границ практически любого элемента. Если для элемента с тенью задан border-radius , то отбрасываемая тень также будет с закруглёнными углами. Порядок наложения нескольких теней такой же, что и у текстовых теней: первая указанная тень будет поверх остальных.
Генератор теней — интерактивный инструмент, позволяющий сгенерировать значение для box-shadow .
Синтаксис
/* Ключевые слова */ box-shadow: none; /* offset-x | offset-y | color */ box-shadow: 60px -16px teal; /* offset-x | offset-y | blur-radius | color */ box-shadow: 10px 5px 5px black; /* offset-x | offset-y | blur-radius | spread-radius | color */ box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2); /* inset | offset-x | offset-y | color */ box-shadow: inset 5em 1em gold; /* Любое количество теней через запятую */ box-shadow: 3px 3px red, -1em 0 0.4em olive; /* Глобальные значения */ box-shadow: inherit; box-shadow: initial; box-shadow: revert; box-shadow: revert-layer; box-shadow: unset;
Каждая тень определяется следующим образом:
Для одновременного создания нескольких теней используйте список значений, разделённых запятыми.
Значения
Если не указано (по умолчанию), то тень будет отбрасываться от элемента (придавая эффект выпуклости блоку). Наличие ключевого слова inset отбрасывает тень внутри элемента (создавая эффект вдавленности блока). Внутренние тени начинаются с рамок элемента (даже если они прозрачные), над фоном элемента, но не под его содержимым.
…для длинного прямого края тени должен быть создан цветовой переход, равный длине расстояния размытия, который перпендикулярен и центрирован по краю тени. Переход начинается от указанного цвета тени в конечной точке радиуса внутри тени до полностью прозрачного цвета в конечной точке пределов радиуса.
Интерполяция
Каждая тень в списке ( none считается за пустой список) интерполируется через значения цвета x, y, радиуса размытия и (когда это допустимо) и радиуса расширения. Для каждой тени, если обе входные тени отмечены как inset или ни одна из них таковой не является, то интерполированная тень будет соответствовать входным теням. Если в любой паре входных теней одна из них является внутренней ( inset ), а другая нет, то список теней не интерполируется. Если количество теней отличается в разных списках, то более короткий список дополняется в конце тенями, цвет которых прозрачен ( transparent ), все значения длин равны 0 , и где inset соответствует более длинному списку.
Формальное определение
Начальное значение | none |
---|---|
Применяется к | все элементы. Это также применяется к ::first-letter . |
Наследуется | нет |
Обработка значения | любая абсолютная длина; работает любой указанный цвет; если другое не указано |
Animation type | список теней |
Формальный синтаксис
box-shadow =
none | (en-US)
# (en-US)
=
? (en-US) && (en-US)
[ (en-US) (en-US) ? (en-US) ? (en-US) ] (en-US) && (en-US)
inset? (en-US)
Примеры
Добавление трёх теней
В этом примере применяется сразу три тени: внутренняя тень, обычная внешняя отбрасываемая тень, а также тень размером 2 пикселя, имитирующая рамку (для создания рамки можно было воспользоваться outline (en-US)).
HTML
blockquote>q>Меня уколют ваши речи,br/> Об ваши взгляды обожгусь,br/> И ранит ложь сильней картечиbr/> Но все равно я поднимусь.q> p>— Майя Энджелоуp> blockquote>
CSS
blockquote padding: 20px; box-shadow: inset 0 -3em 3em rgba(0,0,0,0.1), 0 0 0 2px rgb(255,255,255), 0.3em 0.3em 1em rgba(0,0,0,0.3); >
Результат
Использование нулевых значений для смещений и радиуса размытия
Когда смещение по X ( x-offset ), смещение по Y ( y-offset ) и радиус размытия ( blur ) равны нулю, тень будет представлять собой цветной контур одинакового размера на всех сторонах блока. Тени отображаются с конца списка, поэтому первая тень накладывается поверх последующих. Когда в border-radius указано значение по умолчанию 0 , углы тени становятся прямыми углами. Соответственно, если указать в border-radius любое другое значение, углы станут закруглёнными.
Чтобы тень не перекрывала соседние элементы и не выходила за границу содержащего блока, был добавлен внешний отступ размером, равный самому большому радиусу размытия в списке теней. Тень не влияет на размеры блочной модели.
HTML
How to Set a Box-Shadow Only on the Left and Right Sides
If you want to add a box-shadow only on the left and right sides of an element, we suggest you consider some methods presented in our snippet.
Probably, the best way is using the CSS box-shadow property with the “inset” value. Also, use the :before and :after pseudo-elements, which are absolutely positioned on the right and left sides of the element.
Example of adding a box-shadow on the left and right sides with the :before and :after pseudo-elements:
html> html> head> title>Title of the document title> style> div:before < box-shadow: -20px 0 20px -20px #001f9c inset; content: " "; height: 100%; left: -20px; position: absolute; top: 0; width: 20px; > div:after < box-shadow: 20px 0 20px -20px #001f9c inset; content: " "; height: 100%; position: absolute; top: 0; right: -20px; width: 20px; > div < background: none repeat scroll 0 0 #f0f1f5; height: 120px; margin: 30px; position: relative; width: 120px; > style> head> body> div> div> body> html>
Result
Let’s see another example without the :before and :after pseudo-elements.
Example of adding a box-shadow on the left and right sides:
html> html> head> title>Title of the document title> style> div < box-shadow: 12px 0 15px -4px rgba(0, 55, 162, 0.97), -12px 0 8px -4px rgba(0, 55, 162, 0.97); width: 120px; height: 120px; margin: 30px; background: #f0f1f5; > style> head> body> div> div> body> html>
Note, that in the example above, we also have a little shadow on the top and bottom of the element. But you can add two more box-shadows to the top and bottom to mask the visible top and bottom shadows.
Example of setting a box-shadow on the left and right sides without any shadow on top and bottom:
html> html> head> title>Title of the document title> style> div < box-shadow: 0 9px 0px 0px #f0f1f5, 0 -9px 0px 0px #f0f1f5, 12px 0 15px -4px rgba(0, 55, 162, 0.97), -12px 0 15px -4px rgba(0, 55, 162, 0.97); width: 120px; height: 120px; margin: 30px; background: #f0f1f5; > style> head> body> div> div> body> html>
How to Set a Box-Shadow on One Side of the Element
To set a box-shadow on one side of the element, use the box-shadow property. This property has four length parameters and a color.
Using the box-shadow property follow this syntax:
box-shadow: h-offset v-offset blur spread color;
h-offset sets the shadow horizontally. A positive value sets the right shadow, and a negative value sets the left one.
v-shadow sets the shadow vertically. A positive value sets the shadow below the box, and a negative value sets the shadow above the box.
blur is an optional attribute, which blurs the box-shadow.
spread sets the shadow size.
color is an optional attribute that sets the shadow color.
Let’s start by creating a shadow on the left side of the element. Follow the steps below.
Create HTML
html> html> head> title>Title of the document title> head> body> h1>W3Docs h1> body> html>
Add CSS
- Style the element using the text-align, background, padding-top, color, width and height properties.
- Add the box-shadow property following the syntax mentioned above.
h1 < text-align: center; background: #c4c4c4; padding-top: 50px; color: #000000; width: 400px; height: 120px; box-shadow: -8px 0px 8px #000000; >
Example of adding a box-shadow on the left side of the element:
html> html> head> title>Title of the document title> style> h1 < text-align: center; background: #c4c4c4; padding-top: 50px; color: #000000; width: 400px; height: 120px; box-shadow: -8px 0px 8px #000000; > style> head> body> h1>W3Docs h1> body> html>
Result
Example of adding a box-shadow on the bottom of the element:
html> html> head> title>Title of the document title> style> h1 < text-align: center; background: #c4c4c4; padding-top: 50px; color: #000000; width: 400px; height: 120px; box-shadow: 0 10px 10px #000000; > style> head> body> h1>W3Docs h1> body> html>
When adding a box-shadow only on one side of an element, the focus must be on the last value (the spread radius). It decreases the overall size of the box-shadow, both horizontally and vertically.
Now, we’ll show another example where we use the «inset» value to create a shadow inside the box as the shadow is placed outside the box by default.
Example of adding a box-shadow inside the element:
html> html> head> title>Title of the document title> style> h1 < text-align: center; background: #c4c4c4; padding-top: 50px; color: #000000; width: 400px; height: 120px; box-shadow: 0px 10px 20px #000000 inset; > style> head> body> h1>W3Docs h1> body> html>
In our last example, we use both outside and inside shadows on one side of each presented element.
Example of adding outside and inside shadows:
html> html> head> title>Title of the document title> style> body < background: #ccc; padding: 20px; > .left < float: left; margin-left: 20px; > .box < width: 110px; height: 110px; background: #fff; color: #9e9e9e; margin: 0 auto; margin-bottom: 20px; text-align: center; line-height: 100px; > .shadow-bottom < box-shadow: 0 8px 10px -6px #000000; > .shadow-top < box-shadow: 0 -8px 10px -6px #000000; > .shadow-left < box-shadow: -8px 0 10px -6px #000000; > .shadow-right < box-shadow: 8px 0 10px -6px #000000; > .inner-shadow-bottom < box-shadow: inset 0 8px 10px -6px #000000; > .inner-shadow-top < box-shadow: inset 0 -8px 10px -6px #000000; > .inner-shadow-left < box-shadow: inset 8px 0 10px -6px #000000; > .inner-shadow-right < box-shadow: inset -8px 0 10px -6px #000000; > style> head> body> div class="left"> div class="shadow-bottom box">bottom div> div class="shadow-top box">top div> div class="shadow-left box">left div> div class="shadow-right box">right div> div> div class="left"> div class="inner-shadow-bottom box">top inset div> div class="inner-shadow-top box">bottom inset div> div class="inner-shadow-left box">left inset div> div class="inner-shadow-right box">right inset div> div> body> html>