Window with shadow on html. Inner Shadows in CSS

The CSS box-shadow property allows you to set a shadow for an 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 (than more 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 using the CSS box-shadow property on an html page, when it evenly wraps 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

То же, что и обновление 3, но с современными правилами css (= less), чтобы не требовалось специального позиционирования на псевдоэлементе.

#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; }

ОБНОВЛЕНИЕ 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; }

ОБНОВЛЕНИЕ 2

По-видимому, вы можете сделать это только с дополнительным параметром CSS-тэга box, поскольку все остальные просто указали. Здесь демо:

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

Это было бы лучшим решением. Дополнительный параметр, который добавляется, описывается как:

Четвертая длина - это спрэд расстояние. Положительные значения вызывают теневая форма для расширения направления по указанному радиусу. Отрицательные значения вызывают форму тени договориться.

UPDATE

То, что я сделал, это создать "теневой элемент", который будет скрываться за фактическим элементом, который вы хотели бы иметь в тени. Я сделал ширину "теневого элемента" ровно менее широкой, чем фактический элемент, в 2 раза превышающей указанную тень; затем я выровнял его правильно.

#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; }

Оригинальный ответ

Да, вы можете сделать это с тем же синтаксисом, который вы предоставили. Первое значение контролирует горизонтальное позиционирование, а второе значение контролирует вертикальное позиционирование. Поэтому просто установите первое значение 0px , а второе - произвольное смещение, которое вы хотели бы сделать следующим образом.

С появлением стандарта CSS 3 введено свойство box-shadow , которое получило широкое применение среди веб-разработчиков, так как оно позволяет с легкостью добавить одну или несколько теней к блоку элемента для придания желаемого визуального эффекта.

В предыдущий статье мы с Вами рассматривали свойство border-radius , используя его, вы можете получить тень с закругленными углами. По аналогии с текстовой тенью (text-shadow), вы сможете создавать множественные тени, они наносятся по z-оси спереди назад (с первой заданной тенью сверху).

Давайте детально рассмотрим синтаксис этого современного свойства:


Рассмотрим по порядку возможные значения этого свойства:

Значение Описание
none Тень не отображается. Это значение по умолчанию.
inset Необязательное значение. Если это значение не указано (по умолчанию), то тень будет снаружи элемента и создаст эффект выпуклости элемента. При наличие ключевого слова (значения) inset , тень будет падать внутри элемента и создаст эффект вдавленности. Другими словами, это изменение от наружной тени к внутренней.
h-shadow Обязательное значение. Задаёт расположение горизонтальной тени. Допускается использование отрицательных значений.
v-shadow Обязательное значение. Задаёт расположение вертикальной тени. Допускается использование отрицательных значений.
blur-radius Необязательное значение. Задаёт радиус размытия. Чем больше это значение, тем больше размытие, при этом тень становится больше и светлее. Если значение не задано, то значение будет равно 0 (резкие - отчетливые тени). Отрицательные значения не допускаются.
spread-radius Необязательное значение. Размер тени (радиус растяжения тени). При положительных значениях тень будет расшииряться, а при отрицательных сжиматься. Если значение не задано, то значение будет равно 0 (тень соответствует размеру элемента).
color Необязательное значение. Определяет цвет тени (HEX, RGB, RGBA, HSL, HSLA, "Предопределённые цвета "). Значением по умолчанию является черный.

Основные моменты, которые вам необходимо понять, чтобы создавать тени для элементов:

Хочу обратить Ваше внимание на то, что свойство box-shadow в настоящее время поддерживается всеми современными браузерами:

Свойство
Opera

IExplorer

Edge
box-shadow 10.0
4.0
-webkit-
4.0
3.5
-moz-
10.5 5.1
3.1
-webkit-
9.0 12.0

Если Вы хотите расширить поддержку некоторых браузеров, включая мобильныx IOS 3.2 - 4.3 и Android 2.1 - 3 , то рекомендуется использовать префиксы производителей и использовать следующий синтаксис (в примерах статьи будет использован синтаксис только для современных браузеров):

-webkit-box-shadow : значение ; /* Safari 3.1 - 4, IOS 3.2 - 4.3 и Android 2.1 - 3 */ -moz-box-shadow : значение ; /* Firefox 3.5 - 3.6 */ box-shadow : значение ; /* таблица выше */

Перейдем к практике и начнем с простого примера, в котором добавим по одной тени к элементам:

Пример использования свойства box-shadow в CSS
box-shadow:10px 10px 0px red;
class = "test2" > box-shadow:10px 10px 10px #777;

The result of our example:

Using Multiple Shadows

In the next example, I propose to consider interesting effect mixing colors, which can be achieved by using multiple shadows:

Example of using multiple shadows in CSS (box-shadow property)
  • Two blocks of fixed width and height (15em and 10em), added margins for all sides (2em) and established that the blocks are block-line to be able to line them up.
  • For first block with class .test we indicated four shadows with different horizontal and vertical shadow values ​​so that the element has different shadows on all sides. The blur radius for all shadows was set to the same. The color of each shadow is different and is specified using predefined colors.
  • For second block with class .test2 we indicated four shadows with different horizontal and vertical shadow values. The blur radius for all shadows was set to the same, while the shadow stretch was set to negative, which led to a decrease in the shadow itself. The color of each shadow is different and is specified using the RGBA system.

The result of our example:

Using shadows for images

The final example of this article will focus on using shadows for images. I would like to immediately draw your attention to the fact that directly indicate the shadow for HTML element It won’t work, but we have the opportunity to specify an image as the background for the element we are interested in, and then assign the shadow we need to this element.

We will look at working with background images in detail in the textbook article "", and now, to put an end to the study of using shadows, we will touch on it superficially and use the image as a background to an element in the following example:

An example of using image shadows in CSS
  • Two blocks of fixed width and height (237px and 232px), added margins for all sides (2em) and set the blocks to be block-line to be able to line them up. We set the block size 237px by 232px to the image size so that at this stage training did not have to scale the image to fit the element and affect those CSS properties that are planned to be studied at a later stage (in the textbook article " ").
  • For first block with class .test we indicated null value horizontal and vertical shadow, but at the same time we specified a blur radius of 50px and expanded it by setting a stretch radius of 10px. The shadow color was indicated with a predefined color (violet). In addition, we indicated in the advertisement keyword inset , which causes the shadow to fall inside the element. In other words, we have created an inner shadow of the element.
  • For second block with class .test2 We specified a zero value for the horizontal and vertical shadow, but at the same time we specified a blur radius of 50px and expanded it by setting a stretch radius of 10px. The shadow color is specified in RGBA mode.

The result of our example:

Rice. 98 Example of using shadows for images in CSS (box-shadow property)

Questions and tasks on the topic

Before you start studying next topic take the practical task:


If you have difficulty completing practical task You can always open the example in a separate window and inspect the page to understand what CSS code was used.


2016-2019 Denis Bolshakov, you can send comments and suggestions on the site to [email protected]

Regular shadows are easy to implement using box-shadow or text-shadow. But what if you need to make internal shadows? This article describes how to make these shadows with just a few lines of code.

Syntax

First, let's look at the two main ways to implement shadows in CSS.

box-shadow

Design box-shadow contains several different meanings:

Horizontal offset And vertical offset— horizontal and vertical displacement, respectively. These values ​​indicate which direction the object will cast its shadow:

Blur radius And spread radius a little more complicated. What's the difference? Let's look at an example with two elements, where the values blur radius differ:

The edge of the shadow is simply blurred. With different values spread radius we see the following:

In this case, we see that the shadow is scattered over a large area. If you do not specify a value blur radius And spread radius, then they will be equal to 0.

text-shadow

The syntax is very similar to box-shadow:

The meanings are similar, but not spread-shadow. Usage example:

Inset in box-shadow

To “flip” the shadow inside the object, you need to add inset in CSS:

Once you understand the basic box-shadow syntax, it's very easy to understand how to implement inner shadows. The values ​​are still the same, you can add color (RGB in hex):

Color in RGB format, the alpha value is responsible for the transparency of the shadow:

Images with shadows

Adding an inner shadow to an image is a little more difficult than adding a regular shadow div. To begin with, here is the usual image code:

It is logical to assume that you can add a shadow like this:

Img (
box-shadow: inset 0px 0px 10px rgba(0,0,0,0.5);
}

But the shadow is not visible:

There are several ways to solve this problem, each of which has its pros and cons. Let's look at two of them. The first is to wrap the image in a regular div:



Div (
height: 200px;
width: 400px;
}

img (
height: 200px;
width: 400px;
position: relative;
z-index: -2;
}

Everything works, but you have to add a little extra HTML markup and CSS. The second way is to set the image as the background of the desired block:



Div (
height: 200px;
width: 400px;
background: url(http://lorempixum.com/400/200/transport/2);
box-shadow: inset 0px 0px 10px rgba(0,0,0,0.9);
}

This is what can happen when using inner shadows:

Inset to text-shadow

To implement an inner text shadow, simply add to the code inset does not work:

To solve, first apply to the header h1 install dark background and a light shadow:

H1 (
background-color: #565656;
color: transparent;
}

Here's what happens:

Adding a secret ingredient background-clip which cuts off anything that extends beyond the text (to a dark background):

H1 (
background-color: #565656;
color: transparent;
text-shadow: 0px 2px 3px rgba(255,255,255,0.5);
-webkit-background-clip: text;
-moz-background-clip: text;
background-clip: text;
}

It turned out almost exactly what we needed. Now we just darken the text a little (alpha), and that’s it.

Adds a shadow to an element. It is possible to use several shadows, indicating their parameters separated by commas; when applying shadows, the first shadow in the list will be higher, the last one lower. If a rounding radius is specified for an element via the border-radius property, then the shadow will also have rounded corners. Adding a shadow increases the width of the element, so it may appear horizontal stripe scrolling in the browser.

brief information

Syntax

Box-shadow: none |<тень> [,<тень>]*

Where<тень>:

inset<сдвиг по x> <сдвиг по y> <размытие> <растяжение> <цвет>

Designations

DescriptionExample
<тип> Indicates the type of the value.<размер>
A && BThe values ​​must be output in the order specified.<размер> && <цвет>
A | BIndicates that you need to select only one value from the proposed ones (A or B).normal | small-caps
A || BEach value can be used independently or together with others in any order.width || count
Groups values.[ crop || cross ]
* Repeat zero or more times.[,<время>]*
+ Repeat one or more times.<число>+
? The specified type, word, or group is optional.inset?
(A, B)Repeat at least A, but no more than B times.<радиус>{1,4}
# Repeat one or more times separated by commas.<время>#
×

Values

none Cancels adding a shadow. inset The shadow is drawn inside the element.<сдвиг по x>The horizontal offset of the shadow relative to the element. A positive value of this parameter sets the shadow shift to the right, a negative value - to the left.<сдвиг по y>The vertical offset of the shadow relative to the element. A positive value shifts the shadow down, a negative value shifts it up.<размытие>Sets the shadow blur radius. The higher this value, the more the shadow is smoothed out, becoming wider and lighter. If this parameter is not specified, it defaults to 0 and the shadow will be sharp rather than blurry.<растяжение>A positive value stretches the shadow, a negative value, on the contrary, compresses it. If this parameter is not specified, the default is 0, which will cause the shadow to be the same size as the element.<цвет>Shadow color in any available CSS format, default shadow is black.

It is possible to specify several shadows, separating their parameters with a comma. The following order is taken into account: the first shadow in the list is placed at the very top, the last in the list is at the very bottom.

Example

box-shadow

Would citrus live in the thickets of the south? Yes, but a fake copy!

The result of the example is shown in Fig. 1.

Rice. 1. Type of shadow

Object model

An object.style.boxShadow

Note

Safari before version 5.1, Chrome before version 10.0, Android before version 4.0 support the -webkit-box-shadow property.

Firefox before version 4.0 supports the -moz-box-shadow property.

Internet Explorer prior to version 9.0 does not support the box-shadow property; instead, you can use the filter property:

Filter: progid:DXImageTransform.Microsoft.dropshadow(offX=5, offY=5, color=#000000);

Here: offX - horizontal shadow offset; offY — vertical shadow offset; color — shadow color.

Using the dropshadow filter produces a clear, sharp shadow, so you can use the shadow filter for a blur effect.

Filter: progid:DXImageTransform.Microsoft.shadow(direction=120, color=#000000, strength=10);

Here: direction — shadow direction angle from 0 to 360°; color — shadow color; strength — shadow offset in pixels.

Specification

Each specification goes through several stages of approval.

  • Recommendation - The specification has been approved by the W3C and is recommended as a standard.
  • Candidate Recommendation ( Possible recommendation ) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
  • Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
  • Working Draft - A more mature version of a draft that has been discussed and amended for community review.
  • Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
  • Draft ( Draft specification) - the first draft version of the standard.
×