Shadow on hover in css. Inner Shadows in CSS

Same as Update 3, but with modern rules css (= less) so that no special positioning is required on the pseudo-element.

#box ( background-color: #3D6AA2; width: 160px; height: 90px; position: absolute; top: calc(10% - 10px); left: calc(50% - 80px); ) .box-shadow:after ( content:""; position:absolute; width:100%; bottom:1px; z-index:-1; transform:scale(.9); box-shadow: 0px 0px 8px 2px #000000; )

UPDATE 3

#box ( background-color: #3D6AA2; width: 160px; height: 90px; margin-top: -45px; margin-left: -80px; position: absolute; top: 50%; left: 50%; ) .box- shadow:after ( content: ""; width: 150px; height: 1px; margin-top: 88px; margin-left: -75px; display: block; position: absolute; left: 50%; z-index: -1; -webkit-box-shadow: 0px 0px 8px 2px #000000; -moz-box-shadow: 0px 0px 8px 2px #000000; box-shadow: 0px 0px 8px 2px #000000; )

UPDATE 2

Apparently you can only do this with the optional CSS box tag option, as everyone else just specified. Here's the demo:

Webkit-box-shadow: 0 4px 4px -2px #000000; -moz-box-shadow: 0 4px 4px -2px #000000; box-shadow: 0 4px 4px -2px #000000;

It would be the best solution. Additional parameter which is added is described as:

The fourth length is the spread distance. Positive values ​​cause the shadow shape to expand in direction along the specified radius. Negative values ​​cause the shadow shape to agree.

UPDATE

What I did was create a "shadow element" that would hide behind the actual element you would like to have in the shadow. I made the width of the "shadow element" exactly less wide than the actual element, 2 times the specified shadow; then I aligned it correctly.

#wrapper ( width: 84px; position: relative; ) #element ( background-color: #3D668F; height: 54px; width: 100%; position: relative; z-index: 10; ) #shadow ( background-color: # 3D668F; height: 8px; width: 80px; margin-left: -40px; position: absolute; bottom: 0px; left: 50%; z-index: 5; -webkit-box-shadow: 0px 2px 4px #000000; - moz-box-shadow: 0px 2px 4px #000000; box-shadow: 0px 2px 4px #000000; )

Original answer

Yes, you can do this with the same syntax you provided. The first value controls horizontal positioning, and the second value controls vertical positioning. So just set the first value to 0px and the second to whatever offset you would like to make as follows.

The box-shadow property adds one or more shadows to an element. The shadow is a copy of the element offset by the specified distance. Shadows can be external or internal, blurry or flat, they can follow the contours of blocks with rounded corners. By using keyword inset creates shadows inside the element, making the element visually voluminous or depressed.

How to make a box shadow using the box-shadow property

Browser support

IE: 9.0
Edge: 12.0
Firefox: 4.0, 3.5 -moz-
Chrome: 10.0, 4.0 -webkit-
Safari: 5.1, 3.1 -webkit-
Opera: 11.5
iOS Safari: 5.1, 3.1 -webkit-
Android Browser: 4.0, 2.1 -webkit-

1. Box-shadow property syntax

Each shadow takes from one to five parameters: horizontal offset, vertical offset, blur radius (optional), spread radius (optional), and shadow color. Shadows do not affect the layout and may overlap adjacent elements or their shadows. The property is not inherited.


Rice. 1. Box-shadow property syntax
Values:
x-offset Required value. The horizontal offset of the shadow relative to the block. It can take both positive and negative values, a positive one shifts the shadow to the right of the block, a negative one – to the left.
y-offset Required value. The vertical offset of the shadow relative to the block. Can take both positive and negative values, positive moves the shadow down, negative moves the shadow up.
blur Optional value. Determines the blur radius of the shadow. How larger radius, the more blurred the shadow is. Only positive values ​​can be used.
stretching Optional, expands the shadow by thickening the solid part between blurred edges. Accepts both positive and negative values, specified in length units - px, etc.
color Optional value. By default the shadow is black. To set the value, you can use the following color recording formats: #RRGGBB , rgb(red, green, blue) , rgba(red, green, blue, alpha) . For Safari, the shadow color must be specified.
inset Creates a shadow inside the block.
none The default value means no shadow.
initial Sets the property value to the default value.
inherit Inherits the property value from the parent element.

2. Block shadow examples

2.1. Inner shadow

.example-shadow-1 ( background: #e6e3df; text-align: center; ) .example-shadow-1 span ( margin: 50px; height: 100px; width: 200px; display: inline-block; box-shadow: inset 2px 2px 5px rgba(154, 147, 140, 0.5), 1px 1px 5px rgba(255, 255, 255, 1); )

2.2. Flat shadow on one side

flat

flat

.example-shadow-2 ( background: beige; text-align: center; ) .example-shadow-2 a ( display: inline-block; border-radius: 5px; padding: 15px 35px; font-size: 22px; margin : 20px; color: white; background: #55acee; ​​box-shadow: 0 5px 0 #3C93D5; ) .example-shadow-2 a:hover ( background: #6FC6FF; )

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 shadow CSS property box-shadow 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

  1. ключевое слово inset устанавливает тень внутри элемента;
  2. сдвиг тени по горизонтали (5px - вправо, -5px - влево);
  3. сдвиг по вертикали (5px - вниз, -5px - вверх);
  4. радиус размытия тени (0 - резкая тень);
  5. растяжение тени (5px - растяжение, -5px - сжатие);
  6. цвет тени.

Обязательно следует указать только сдвиг по горизонтали и вертикали, все остальные параметры будут приниматься по умолчанию. В этом случае тень будет резкой без размытия и чёрного цвета.

За счёт комбинаций разных параметров и их значений можно получить широкое разнообразие видов теней. В табл. 1 представлен код и результат, к которому он приводит.

Табл. 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 enemy 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



Result this example 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 browser window and thus lead to the appearance horizontal stripe scroll.

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

Block with shadow

Heading

Block content


An element can have more than one shadow, but several at once; 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

Image



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.