The CSS box-shadow property allows you to set a shadow html element. It is used quite often by website designers to somehow decorate and highlight frames with text, images, and make content more readable.
CSS box-shadow syntax
... box-shadow : X Y R1 R2 color ; ...
- X - offset along the X axis (horizontal)
- Y - offset along the Y axis (vertical)
- R1 - blur (the higher the value, the smoother the transition)
- R2 - radius of extension (if positive, it stretches, negative, it compresses)
- color - color (can be specified in any format: #RGB, color name)
- inset - if this value is present, the shadow will be located inside the block (element)
Example 1. HTML frame with box-shadow without offset
Below is the simplest way to use a shadow with the CSS box-shadow property on html page when it evenly flows around the entire frame without displacement.
Пример №1. Рамка с тенью
Пример №1. Рамка с тенью
Пример 2. HTML рамка со смещенной тенью box-shadow
Практически тот же пример, что и первый, но только со смещением рамки.
Пример №2. Рамка со смещенной тенью
На странице преобразуется в следующее
Пример №2. Рамка со смещенной тенью
Пример №3. Свечение рамки html
Реализация тени в виде свечения
Пример №3. Свечение
На странице преобразуется в следующее
Пример №3. Свечение
Пример 4. Внутреннее свечение границы html
Свечение, которое направлено внутрь блока и никак не выходит за его пределы. Эффект создается за счет атрибута inset .
Пример №4. Внутреннее свечение
На странице преобразуется в следующее
Пример №4. Внутреннее свечение
Пример 5. Совмещение теней в html
Эффект тени можно совмещать через запятую. В таком случае образуется очень интересные результаты. Например, можно сделать разноцветную рамку в стиле 3D.
Пример №5. Совмещение теней
На странице преобразуется в следующее
Пример №5. Совмещение теней
Примечание: старые браузерыIE младше 9 версии не поддерживают box-shadow. Префиксы браузеров для box-shadow
- -webkit-box-shadow - для Chrome до 10, Safari до 5.1, Android до 4 и iOS до 5
- -moz-box-shadow - для Firefox до версии 4.0
Тень под блочным элементом на странице обычно применяется для создания эффекта трёхмерности, привлечения внимания к элементу или как часть дизайна. Небольшая тень под элементами придаёт также странице объём и глубину.
Для добавления тени используется свойство box-shadow , у которого имеется шесть значений, из них только два являются обязательными. На рис. 1 показано свойство box-shadow со всеми возможными значениями, они пронумерованы для их идентификации.
Рис. 1. Значения свойства box-shadow
- ключевое слово inset устанавливает тень внутри элемента;
- сдвиг тени по горизонтали (5px - вправо, -5px - влево);
- сдвиг по вертикали (5px - вниз, -5px - вверх);
- радиус размытия тени (0 - резкая тень);
- растяжение тени (5px - растяжение, -5px - сжатие);
- цвет тени.
Обязательно следует указать только сдвиг по горизонтали и вертикали, все остальные параметры будут приниматься по умолчанию. В этом случае тень будет резкой без размытия и чёрного цвета.
За счёт комбинаций разных параметров и их значений можно получить широкое разнообразие видов теней. В табл. 1 представлен код и результат, к которому он приводит.
Код | Результат | Описание |
---|---|---|
box-shadow: 5px 5px; | Резкая тень справа и снизу. | |
box-shadow: -5px -5px; | Резкая тень слева и сверху. | |
box-shadow: 0 0 5px; | Размытая тень вокруг элемента. | |
box-shadow: 0 0 5px 2px; | Расширение тени на 2 пиксела. | |
box-shadow: 0 0 5px 2px red; | Красное свечение вокруг элемента. | |
box-shadow: 0.4em 0.4em 5px rgba(122,122,122,0.5); | Полупрозрачная тень. | |
box-shadow: inset 0 0 6px; | Тень внутри. |
Как видно из таблицы, сдвиг тени не обязательно задавать в пикселах, хотя это и удобно. Цвет тени можно указывать в любом доступном формате, так, для получения полупрозрачной тени подойдёт формат RGBA, такая тень будет хорошо смотреться на любом фоне. В примере 1 показано, как это сделать.
Пример 1. Тень на фоновом рисунке
HTML5 CSS3 IE 9+ Cr Op Sa Fx
Do not go against the enemy’s banners when they are in perfect order; do not attack the enemy’s camp when it is impregnable; this is change management.
Sun Tzu, trans. Nikolai Konrad
The result of this example is shown in Fig. 2. The shadow follows the rounding of the corners of the block.
Rice. 2. Appearance of shadow on the background picture
When adding a "wide" shadow, be aware that it may extend beyond the visible borders of the browser window and thus result in a horizontal scrollbar appearing.
Shadows can also be added to pseudo-elements; this is sometimes required for complex layouts. In Fig. Figure 3 shows a header block with a shadow added to it. To avoid any lines at the junction, you have to use the ::after pseudo-element and add a shadow to it.
Rice. 3. Block with shadow
Example 2 shows the creation of such a block.
Example 2. Block with shadow
HTML5 CSS3 IE 9+ Cr Op Sa Fx
Heading
An element can have more than one shadow; their parameters are listed separated by commas in the value of the box-shadow property. Example 3 shows how to add a double shadow to all images.
Example 2. Block with shadow
HTML5 CSS3 IE 9+ Cr Op Sa Fx
The result of this example is shown in Fig. 4.
Rice. 4. Double Shadow Image
The first shadow is displayed to the left of the image with a blur radius of 20px, its size reduced by the fourth parameter (-20px). The parameters of the second shadow are indicated after the decimal point; the shadow is displayed to the right of the picture and is also reduced for symmetry.
Today we will learn how to make CSS shadows without images. After completing this tutorial, you will no longer need a CSS shadow generator.
The main advantage of shadows created using CSS3 is the ease of implementation and the reduction in the number of requests to the server (since we no longer use images). To make a CSS shadow we need a div tag and a CSS box-shadow property. You won't need any additional markup because we'll create :after and :before pseudo elements that we'll place behind the main object (a div with the class block).
Take a look at the HTML code for which we will create a CSS3 shadow:
Content
Next you can see ready-made examples and the code needed to implement them. In order to minimize the text on the page, we will omit CSS properties with browser prefixes. Full code You can see it by clicking on the “Example” link corresponding to the example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; border-radius:4px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3) , 0 0 40px rgba(0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; bottom:15px; left:10px ; width:50%; height:20%; box-shadow:0 15px 10px rgba(0, 0, 0, 0.7); transform:rotate(-3deg); :10px;left:auto;rotate(3deg);.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; border:1px solid #efefef; border-radius:0 0 120px 120px / 0 0 6px 6px ) .block:before, .block:after ( content:""; position:absolute ; z-index:-2; left:10px; height:55%; box-shadow:0 8px 12px rgba(0, 0, 0, 0.5); transform:skew(-8deg) rotate(-3deg); .block:after ( right:10px; left:auto; transform:skew(8deg) rotate(3deg); )
Using a shadow you can give a block perspective. See example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; ) .block:before ( left:80px; bottom:5px ; width:50%; height:35%; max-width:-80px 0 8px rgba(0, 0, 0, 0.4); transform-origin:0 100% ; ) .block:after ( display:none; )
CSS shadow for the raised block. See example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; box-shadow: 0 15px 10px -10px rgba(0, 0, 0, 0.5), 0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0 , 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; )
Example CSS3 shadow for a vertically folded block. See example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; ) .block:before ( top:10px; bottom:10px ; left:0; right:50%; box-shadow:0 0 15px rgba(0,0,0,0.6); border-radius:10px / 100px;
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; ) .block:before ( top:10px; bottom:10px ; left:0; right:0; box-shadow:0 0 15px rgba(0,0,0,0.6); border-radius:10px / 100px;
Example CSS3 shadow for a horizontally folded block. See example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; ) .block:before ( top:50%; bottom: 0px; left:10px; box-shadow:0 0 15px rgba(0,0,0,0.6); border-radius:100px / 10px;
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba( 0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; ) .block:before ( top:0px; bottom:0px ; left:10px; right:10px; box-shadow:0 0 15px rgba(0,0,0,0.6); border-radius:100px / 10px;
CSS3 shadow for rotated block. See example.
.block ( position:relative; width:40%; padding:1em; margin:2em 10px 4em; background:#fff; border-radius:4px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3) , 0 0 40px rgba(0, 0, 0, 0.1) inset; box-shadow:none; transform:rotate(-3deg); .block > :first-child:before ( content:""; position:absolute; z-index:-1; bottom:0; right:0px; box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba (0, 0, 0, 0.1) inset; ) .block:before, .block:after ( content:""; position:absolute; z-index:-2; bottom:15px; left:10px; width:50% ; height:20%; max-width:300px; box-shadow:0 15px 10px rgba(0, 0, 0, 0.7); transform:rotate(-3deg); auto; transform:rotate(3deg);
The order of recording is fundamentally important. The first value is always the offset along the X axis, the second - along the Y axis.
If an offset is not needed along one of the axes, set it to zero:
Class(box-shadow: 0 8px;) – shift the shadow only along the Y axis
Result
Class(box-shadow: 8px 8px;) – shift along both axes
Result
Negative value for box-shadow axes
The shadow will move in the opposite direction:
Class(box-shadow: -8px 8px;) – shift the shadow with a negative value along the X axis
Result
Shadow Blur Radius
Third property parameter box-shadow. If not specified, the value is 0 and the shadow size is equal to the size of the element it is applied to.
Class(box-shadow: 0 48px 0;) – the shadow duplicates the dimensions of the element to which it is applied
Result
When the value is greater than zero, the edges lose definition, the shadow becomes larger and visually lighter. Blur is applied from all sides:
Class(box-shadow: 0 0 8px;) – no offset, only blur
Result
Class(box-shadow: 0 8px 8px;) – Y-axis offset and blur
Result
A negative value is considered an error and the shadow will not be displayed at all.
Shadow stretch radius
Fourth property parameter box-shadow. Changes the size of the shadow relative to the element. Stretches in all directions:
Class(box-shadow: 0 0 0 8px;) – no displacement or blur, only stretching
Result
In this case, the shadow is 16 pixels larger than the element in width and height: 8px left + 8px right and 8px top + 8px bottom.
Negative shadow stretch value in CSS
The shadow does not stretch, but narrows on all sides by the specified value:
Class(box-shadow: 0 16px 0 -8px;) – decrease the shadow with a negative value
Result
Shadow color
By default, the shadow color duplicates the font color: as in the examples above.
The shadow color is specified in any available CSS format:
- #ff0009
- rgb(255, 0, 9)
- hsl(358, 100%, 50%);
Give the element a blue shadow:
Class(box-shadow: 0 8px #3a8fe7;)
Result
Inner shadow
Parameter inset displays a shadow inside the block.
Unlike the options listed above, there is no strict writing order. Both options will give the same result:
Box-shadow: 0 8px #3a8fe7 inset; box-shadow: inset 0 8px #3a8fe7;
Result
The second option is easier to understand when reading the code.
Several shadows
Multiple shadows are specified separated by commas. Display order from top to bottom:
Class( box-shadow: 0 8px #3a8fe7, 0 16px #3ae7af; )
Result
If you switch places, the blue shadow will not be visible:
Class( box-shadow: 0 16px #3ae7af, 0 8px #3a8fe7; )
Result
The inner and outer shadow are set at the same time:
Class( box-shadow: 0 16px #3ae7af, inset 0 8px #3a8fe7; )
Result
Rounded shadow
If an element is given the property border-radius, the shadow will have rounded corners.
Class( box-shadow: 0 16px #3a8fe7; border-radius: 8px; )
Result
By setting the shadow stretch, we also increase its rounding. For example, border-radius is 8px and shadow stretch is 4.
8+4=12px is the rounding radius of the shadow.
Class( box-shadow: 0 16px 0 4px #3a8fe7; border-radius: 8px; )
Result
The same principle applies to shrinking the shadow when the value is negative.
8+(-4)=4px - we get a shadow rounding that is twice as small.
If the shadow compression is greater than border-radius, we will get a shadow with right angles. For example, compression is 16px.
8+(-16)=(-8), but fillet cannot have a negative value and zero will be applied.
Class( box-shadow: 0 24px 0 -16px #3a8fe7; border-radius: 8px; )
Result
CSS property box-shadow Supported by all popular browsers except Opera Mini.
Reviews