- CSS box-shadow Property
- Browser Support
- CSS Syntax
- Property Values
- More Examples
- Example
- CSS box-shadow генератор
- Синтаксис
- Горизонтальное смещение (по оси X)
- Вертикальное смещение (по оси Y)
- Размытие
- Растяжение
- Цвет
- Внешняя/внутренняя
- Несколько теней
- Круглая тень
- Эффект увеличения с тенью
- Эффект парения элемента с помощью box-shadow
- Тень и свойство clip-path
- box-shadow
- Try it
- Syntax
- Values
- Interpolation
- Formal definition
- Formal syntax
- Examples
- Setting three shadows
- HTML
- CSS
- Result
- Setting zero for offset and blur
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
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:
CSS box-shadow генератор
box-shadow — это CSS3 свойство, которое позволяет создавать эффект тени для, практически, любого элемента веб страницы. Оно похоже на эффект Drop Shadows в Photoshop, с помощью этого свойства создается иллюзия глубины на 2-мерных страницах.
Синтаксис
Свойство принимает составное значение из пяти разных частей: горизонтальное смещение, вертикальное смещение, размытие, растяжение, цвет тени. К тому же можно указать будет ли тень внешней или внутренней.
CSS div { box-shadow: offset-x offset-y blur spread color position; }
В отличие от других свойств, каких как border, которые разбиты на подсвойства (border-width, border-style и тд), box shadow CSS стоит особняком. Соответственно, важен порядок, в котором вы записываете значения свойства.
Горизонтальное смещение (по оси X)
Первое значение offset-x — смещение тени по оси X. Положительное значение сместит тень вправо, а отрицательное — влево.
CSS .box-1 { box-shadow: -15px 0 10px 0 rgba(0,0,0,0.2); } .box-2 { box-shadow: 15px 0 10px 0 rgba(0,0,0,0.2); }
Вертикальное смещение (по оси Y)
Второе значение offset-y — смещение тени по оси Y. Положительное значение сместит тень вниз, а отрицательное — наверх.
CSS .box-1 { box-shadow: 0 15px 10px 0 rgba(0,0,0,0.2); } .box-2 { box-shadow: 0 -15px 10px 0 rgba(0,0,0,0.2); }
Размытие
Третье значение (blur) представляет собой радиус размытия тени, посмотрите как он работает на box shadow генераторе выше. Значение 0 означает, что тень будет совсем не размыта, края и стороны будут абсолютно четкие. Чем выше значение, тем более мутную и размытую тень вы получите. Отрицательные значения не допускаются.
CSS .box-1 { box-shadow: 0 5px 0 0 rgba(0,0,0,0.2); } .box-2 { box-shadow: 0 5px 15px 0 rgba(0,0,0,0.2); } .box-3 { box-shadow: 0 5px 30px 0 rgba(0,0,0,0.2); }
Растяжение
Четвертое значение (spread) представляет собой размер тени или дистанции от тени до элемента. При положительном значении тень увеличится, выйдет за пределы элемента. Отрицательное значение уменьшит и сожмет тень.
CSS .box-1 { box-shadow: 0 0 5px 0 rgba(0,0,0,0.2); } .box-2 { box-shadow: 0 0 5px 5px rgba(0,0,0,0.2); } .box-3 { box-shadow: 0 0 5px -15px rgba(0,0,0,0.2); }
Цвет
Цвет тени может быть абсолютно любым и записан в разных форматах, доступных в CSS (HEX, RGB, RGBA и пр), попробуйте разные оттенки в css box shadow generator.
CSS .box-1 { box-shadow: 0 10px 5px -5px #e6ecc1; } .box-2 { box-shadow: 0 10px 5px -5px rgba(30, 129, 204, 0.2); }
Внешняя/внутренняя
Значение inset определяет положение тени. По умолчанию оно не указано, это означает, что тень будет снаружи элемента. Для того, чтобы тень была внутри элемента, необходимо в конце добавить ключевое слово inset.
CSS .box-1 { box-shadow: 10px 10px 10px 2px rgba(34, 60, 80, 0.2) inset; } .box-2 { box-shadow: 10px 10px 10px 2px rgba(34, 60, 80, 0.2); }
Несколько теней
В CSS тень блока может быть не одна. Чтобы добавить несколько теней, достаточно написать их в одном свойстве через запятую.
CSS .box-1 { box-shadow: 10px 10px 10px 2px rgba(34, 60, 80, 0.2) inset, 10px 10px 10px 2px rgba(34, 60, 80, 0.2); }
Круглая тень
Тень может быть круглой, для этого достаточно добавить свойство border-radius
CSS .box-1 { box-shadow: 10px 10px 10px 0px rgba(34, 60, 80, 0.2); border-radius: 50%; }
Эффект увеличения с тенью
Используя свойства box-shadow и transform, можно создать иллюзию приближения и отдаления элемента от пользователя.
CSS .box-1 { transform: scale(1); box-shadow: 0 0 5px 5px rgba(34, 60, 80, 0.2); transition: box-shadow 0.5s, transform 0.5s; } .box-1:hover { ransform: scale(1.2); box-shadow: 0 0 15px 7px rgba(34, 60, 80, 0.2); transition: box-shadow 0.5s, transform 0.5s; }
Эффект парения элемента с помощью box-shadow
Мы можем добавить тень к псевдоэлементу :after и создать тень ниже элемента. Тем самым создавая иллюзию, что элемент был поднят вверх, а потом упал.
CSS .box-1 { position: relative; transform: translateY(0); transition: transform 1s; } .box-1::after { content: ""; display: block; position: absolute; bottom: -30px; left: 50%; height: 8px; width: 100%; box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.4); border-radius: 50%; background-color: rgba(0, 0, 0, 0.2); transform: translate(-50%, 0); transition: transform 1s; } .box-1:hover { transform: translateY(-40px); transition: transform 1s; } .box-1:hover::after { transform: translate(-50%, 40px) scale(0.75); transition: transform 1s; }
Тень и свойство clip-path
Тень возможно сделать не только на элементах в виде блока или круга, но и на более сложных формах с использованием свойства clip-path . Правда свойство box-shadow при этом не сработает и нам придется заменить его другим. Приступим, создадим элемент box-1.
CSS .box-1 { clip-path: polygon(30px 0%, 100% 0%, 100% 100%, 30px 100%, 0 50%); }
В CSS существует фильтр, который тоже делает CSS тень блока — drop-shadow() . Но у вас не поучится использовать его непосредственно на элементе, так как clip-path просто отрежет эту тень. Поэтому создаем родительский блок и наложим тень на него.
CSS .box-1__wrapper { filter: drop-shadow(-1px 6px 3px rgba(34, 60, 80, 0.2)); } .box-1 { clip-path: polygon(30px 0%, 100% 0%, 100% 100%, 30px 100%, 0 50%); }
- Студия Профессиональная разработка сайтов под заказ Подробнее
- Иконки Прекрасный способ визуально выразить главную мысль Подробнее
- Сервисы Полезные инструменты для веб разработчиков Подробнее
- Блог Делимся в опытом и знанием в IT сфере Подробнее
- Поделиться ВконтактеFacebook Контакты support@active-vision.ru
© 2019 — 2023 Active-Vision. Политика конфиденциальности. Вся информация на сайте носит справочный характер и не является публичной офертой, определяемой статьей 437 ГК РФ
box-shadow
The box-shadow CSS property adds shadow effects around an element’s frame. You can set multiple effects separated by commas. A box shadow is described by X and Y offsets relative to the element, blur and spread radius, and color.
Try it
The box-shadow property enables you to cast a drop shadow from the frame of almost any element. If a border-radius is specified on the element with a box shadow, the box shadow takes on the same rounded corners. The z-ordering of multiple box shadows is the same as multiple text shadows (the first specified shadow is on top).
Box-shadow generator is an interactive tool allowing you to generate a box-shadow .
Syntax
/* Keyword values */ 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; /* Any number of shadows, separated by commas */ box-shadow: 3px 3px red, -1em 0 0.4em olive; /* Global values */ box-shadow: inherit; box-shadow: initial; box-shadow: revert; box-shadow: revert-layer; box-shadow: unset;
Specify a single box-shadow using:
To specify multiple shadows, provide a comma-separated list of shadows.
Values
If not specified (default), the shadow is assumed to be a drop shadow (as if the box were raised above the content). The presence of the inset keyword changes the shadow to one inside the frame (as if the content was debossed inside the box). Inset shadows are drawn inside the border (even transparent ones), above the background, but below content.
If both and are set to 0 , the shadow is placed behind the element (and may generate a blur effect if and/or is set).
…for a long, straight shadow edge, this should create a color transition the length of the blur distance that is perpendicular to and centered on the shadow’s edge, and that ranges from the full shadow color at the radius endpoint inside the shadow to fully transparent at the endpoint outside it.
Interpolation
When animating shadows, such as when multiple shadow values on a box transition to new values on hover, the values are interpolated. Interpolation determines intermediate values of properties, such as the blur radius, spread radius, and color, as shadows transition. For each shadow in a list of shadows, the color, x, y, blur, and spread transition; the color as , and the other values as s.
In interpolating multiple shadows between two comma-separated lists of multiple box shadows, the shadows are paired, in order, with interpolation occurring between paired shadows. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is transparent , and X, Y, and blur are 0 , with the inset, or lack of inset, being set to match. If, in any pair of shadows, one has inset set and the other is does not, the entire shadow list is uninterpolated; the shadows will change to the new values without an animating effect.
Formal definition
Initial value | none |
---|---|
Applies to | all elements. It also applies to ::first-letter . |
Inherited | no |
Computed value | any length made absolute; any specified color computed; otherwise as specified |
Animation type | a shadow list |
Formal syntax
Examples
Setting three shadows
In this example, we include three shadows: an inset shadow, a regular drop shadow, and a 2px shadow that creates a border effect (we could have used an outline instead for that third shadow).
HTML
blockquote> q> You may shoot me with your words,br /> You may cut me with your eyes,br /> You may kill me with your hatefulness,br /> But still, like air, I'll rise. q> p>— Maya Angeloup> 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); >
Result
Setting zero for offset and blur
When the x-offset , y-offset , and blur are all zero, the box shadow will be a solid-colored outline of equal-size on all sides. The shadows are drawn back to front, so the first shadow sits on top of subsequent shadows. When the border-radius is set to 0, as is the default, the corners of the shadow will be, well, corners. Had we put in a border-radius of any other value, the corners would have been rounded.
We added a margin the size of the widest box-shadow to ensure the shadow doesn’t overlap adjacent elements or go beyond the border of the containing box. A box-shadow does not impact box model dimensions.
HTML
CSS
p box-shadow: 0 0 0 2em #f4aab9, 0 0 0 4em #66ccff; margin: 4em; padding: 1em; >
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
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.