Изучаем css: тень блока

All CSS Text Properties

Property Description
color Sets the color of text
direction Specifies the text direction/writing direction
letter-spacing Increases or decreases the space between characters in a text
line-height Sets the line height
text-align Specifies the horizontal alignment of text
text-decoration Specifies the decoration added to text
text-indent Specifies the indentation of the first line in a text-block
text-shadow Specifies the shadow effect added to text
text-transform Controls the capitalization of text
text-overflow Specifies how overflowed content that is not displayed should be signaled to the user
unicode-bidi Used together with the direction property to set or return whether the text should be overridden to support multiple languages in the same document
vertical-align Sets the vertical alignment of an element
white-space Specifies how white-space inside an element is handled
word-spacing Increases or decreases the space between words in a text

❮ Previous
Next ❯

Примеры

Пример

Добавить эффект размытия к тени:

#example1 {  box-shadow: 10px 10px 8px #888888;
}

Пример

Определить радиус распространения тени:

#example1 {  box-shadow: 10px 10px 8px 10px #888888;
}

Пример

Определить несколько теней:

#example1 {  box-shadow: 5px 5px blue, 10px 10px
red, 15px 15px green;
}

Пример

Добавить врезное ключевое слово::

#example1 {  box-shadow: 5px 10px inset;}

Пример

Изображения брошены на стол. В этом примере показано, как создавать «полароидные» изображения и поворачивать их:

div.polaroid {  width: 284px; 
padding: 10px 10px 20px 10px;  border: 1px solid
#BFBFBF;  background-color: white;  box-shadow: 10px 10px 5px #aaaaaa;}

Как сделать тень в CSS — два варианта реализации

Vertical offset и horizontal offset — это вертикальное и горизонтальное смещение. С помощью этих параметров мы задаем направление, в котором объект будет отбрасывать тень:

Чтобы сделать жесткую CSS тень, установите степень размытия или вообще не задавайте это значение. Если требуется задать несколько свойств блока, укажите их через запятую.

Тени текста в CSS — text-shadow

Свойство text-shadow поддерживают все популярные браузеры (Google Chrome, Firefox, Opera, Safari). Text-shadow имеет четыре параметра:

  • Смещение по горизонтали (положительное – вправо, отрицательное – влево);
  • Смещение по вертикали (положительное — вниз, отрицательное – вверх);
  • Радиус размытия;
  • Цвет тени.

По синтаксису text-shadow во многом напоминает box-shadow:

При этом spread-shadow отсутствует. Вот так это может выглядеть на примере:

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthobject-fitopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapz-index

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Синтаксис

Чтобы задать одну тень, можно использовать:

  • Два, три и четыре значения .

    • Если задано только два значения, они интерпретируется как values.
    • Если задано третье значение, оно понимается как .
    • Если задано четвёртое значение, оно интерпретируется .
  • Дополнительно, можно задать ключевое слово .
  • Дополнительно, можно задать значение .

Чтобы задать несколько теней, перечислите их через запятую.

Если ключевое слово не указано (по умолчанию), тень будет снаружи элемента (и создаст эффект выпуклости блока).
При наличие ключевого слова , тень будет падать внутри блока и создаст эффект вдавленности блока. Inset-тени рисуются в пределах границ элемента (даже прозрачные), поверх фона и за контентом.
Существуют 2 значения , которые устанавливают смещение тени. определяет горизонтальное расстояние. Отрицательные значения располагают тень слева от элемента. определяет вертикальное расстояние. Отрицательные значения располагают тень выше элемента. Посмотрите какие единицы можно задать.
Если оба значения равны , то тень расположится за элементом (и будет отображаться размытие, если и/или установлены).
Это третье значение . Чем больше это значение, тем больше и светлее размытие. Отрицательные значения не поддерживаются. Если не определено, будет использоваться (резкий край тени). Спецификация не содержит в себе точного алгоритма расчёта размытости теней, однако, в ней указано следующее:
Это четвёртое значение . Положительные значения увеличивают тень, отрицательные — сжимают. По умолчанию значение равно (размер тени равен размеру элемента).
Смотрите возможные ключевые слова и нотации для .
Если не указано, используемый цвет будет зависеть от браузера — обычно будет применено значение свойства (en-US), но Safari в настоящее время рисует прозрачную тень в этом случае.

Each shadow in the list (treating as a 0-length list) is interpolated via the color (as color) component, and x, y, blur, and (when appropriate) spread (as length) components. For each shadow, if both input shadows are or are not , then the interpolated shadow must match the input shadows in that regard. If any pair of input shadows has one and the other not , the entire shadow list is uninterpolable. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is , all lengths are , and whose (or not) matches the longer list.

none  

где

где

где

где

CSS Справочники

CSS СправочникCSS ПоддержкаCSS СелекторыCSS ФункцииCSS ЗвукCSS Веб шрифтыCSS АнимацииCSS ДлиныCSS Конвертер px-emCSS Названия цветаCSS Значения цветаCSS по умолчаниюCSS Символы

CSS Свойства

align-content
align-items
align-self
all
animation
animation-delay
animation-direction
animation-duration
animation
-fill-mode
animation-iteration-count
animation-name
animation-play-state
animation-timing-function
backface-visibility
background
background-attachment
background-blend-mode
background-clip
background-color
background-image
background-origin
background-position
background-repeat
background-size
border
border-bottom
border-bottom-color
border-bottom-left-radius
border-bottom-right-radius
border-bottom-style
border-bottom-width
border-collapse
border-color
border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-left
border-left-color
border-left-style
border-left
-width
border-radius
border-right
border-right-color
border-right-style
border-right-width
border-spacing
border-style
border-top
border-top-color
border-top-left-radius
border-top-right-radius
border-top-style
border-top-width
border-width
bottom
box-decoration-break
box-shadow
box-sizing
caption-side
caret-color
@charset
clear
clip
color
column-count
column-fill
column-gap
column-rule
column-rule-color
column-rule-style
column-rule-width
column-span
column-width
columns
content
counter-increment
counter-reset
cursor
direction
display
empty-cells
filter
flex
flex-basis
flex-direction
flex-flow
flex-grow
flex-shrink
flex-wrap
float
font
@font-face
font-family
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-weight
grid
grid-area
grid-auto-columns
grid-auto-flow
grid-auto-rows
grid-column
grid-column-end
grid-column-gap
grid-column-start
grid-gap
grid-row
grid-row-end
grid-row-gap
grid-row-start
grid-template
grid-template
-areas
grid-template-columns
grid-template-rows
hanging-punctuation
height
hyphens
@import
isolation
justify-content
@keyframes
left
letter-spacing
line-height
list-style
list-style-image
list-style-position
list-style
-type
margin
margin-bottom
margin-left
margin-right
margin-top
max-height
max-width
@media
min-height
min-width
mix-blend-mode
object-fit
object-position
opacity
order
outline
outline-color
outline-offset
outline-style
outline-width
overflow
overflow-x
overflow-y
padding
padding-bottom
padding-left
padding-right
padding-top
page-break-after
page-break-before
page-break-inside
perspective
perspective-origin
pointer-events
position
quotes
resize
right
tab-size
table-layout
text-align
text-align-last
text-decoration
text-decoration-color
text-decoration-line
text-decoration-style
text-indent
text-justify
text-overflow
text-shadow
text-transform
top
transform
transform-origin
transform-style
transition
transition-delay
transition-duration
transition-property
transition-timing-function
unicode-bidi
user-select
vertical-align
visibility
white-space
width
word-break
word-spacing
word-wrap
writing-mode
z-index

CSS Properties

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Расширенное задание параметров box-shadow

В этом свойстве можно так же указать размытие и цвет тени блока. В этом случае наше свойство будет выглядеть вот так:

CSS

box-shadow: 10px 10px 5px #cccссс;

1 box-shadow10px10px5px#cccссс;

Значение 5px задает размытие тени, а #cccссс – цвет тени в шестнадцатеричной системе.

Для задания смешения и размытия мы можем указывать величину в пикселях или относительных единицах измерения (em).

Цвет так же можно задавать различными способами. Мы можем задать цвет тени шестнадцатеричным значением, использовать формат RGB или же можно задать полупрозрачную тень с помощью формата RGBA. Например, вот так:

CSS

box-shadow: 10px 10px 5px rgba (120,120,120,0.5);

1 box-shadow10px10px5pxrgba(120,120,120,0.5);

Здесь первый три цифры (120,120,120) – это значения цветов красный, зелёный, синий.
Последнее число (0.5) – это уровень прозрачности, который может иметь значения от 0 до 1

Для точного определения шестнадцатеричного значения цвета вы можете воспользоваться одним из инструментов, описанных в этой статье.

И тогда мы получим такой результат:

Красивая тень CSS3

Интегрируйте CSS с HTML-страницей

Теперь вы знаете, как добавлять классные эффекты тени блока с помощью CSS, вы можете легко интегрировать их с элементами HTML разными способами.

Вы можете встроить его в саму HTML-страницу или прикрепить как отдельный документ. Есть три способа включить CSS в HTML-документ:

Внутренний CSS

Встроенные или внутренние таблицы стилей вставляются в раздел <head> HTML-документа с помощью элемента <style> . Вы можете создать любое количество элементов <style> в документе HTML, но они должны быть заключены между тегами <head> и </head> . Вот пример, демонстрирующий, как использовать внутренний CSS с HTML-документом:

Встроенный CSS

Встроенный CSS используется для добавления уникальных стилевых правил к элементу HTML. Его можно использовать с элементом HTML через атрибут стиля . Атрибут style содержит свойства CSS в форме «свойство: значение», разделенные точкой с запятой ( ; ).

Все свойства CSS должны быть в одной строке, т.е. между свойствами CSS не должно быть разрывов строк. Вот пример, демонстрирующий, как использовать встроенный CSS с HTML-документом:

Внешний CSS

Внешний CSS – это наиболее идеальный способ применения стилей к HTML-документам. Внешняя таблица стилей содержит все правила стилей в отдельном документе (файле .css), затем этот документ связывается с документом HTML с помощью тега <link> . Этот метод – лучший метод определения и применения стилей к HTML-документам, так как затронутый HTML-файл требует минимальных изменений в разметке. Вот пример, демонстрирующий, как использовать внешний CSS с HTML-документом:

Создайте новый файл CSS с расширением .css . Теперь добавьте в этот файл следующий код CSS:

Наконец, создайте документ HTML и добавьте в него следующий код:

Обратите внимание, что файл CSS связан с документом HTML через тег и атрибут href. Все три вышеупомянутых метода (внутренний CSS, встроенный CSS и внешний CSS) будут отображать один и тот же вывод –

Все три вышеупомянутых метода (внутренний CSS, встроенный CSS и внешний CSS) будут отображать один и тот же вывод –

Вариации

Дальше мы будем по-разному изменять цвет фона элемента body. Делаем мы это потому, что для некоторых теней CSS нужен определенный фон, иначе они не будут заметны.

Чтобы текст смотрелся красивее, мы зададим его в верхнем регистре.

Эффект оттиска

Установите для цвета текста немного более темный оттенок, чем фон.

Затем примените небольшую белую тень текста с уменьшенной непрозрачностью:

body {
	background: #222;
}
.text {
	font-size: 5em; 					
	color: rgba(0,0,0,0.6);		/* цвет текста */
    text-shadow: 2px 2px 3px rgba(255,255,255,0.1);	/* добавление тени */
}

Используя код RGBA, вы можете установить непрозрачность цвета

Обратите внимание на то, что цвет текста имеет непрозрачность 60% (0.6), а тени div CSS 10% (0.1)

Эффект оттиска букв

-webkit-background-clip: text

Функция, о которой мы, кажется, упомянули в свойстве  для значения . Опция  позволяет обрезать фоновые изображения под форму текста. Это неофициальный стандарт, но он был подключён во множестве браузеров. В данном контексте обязательно используется префикс  для любых браузеров:

Так почему остальные браузеры используют префикс ? В основном для совместимости — поэтому многие веб-разработчики стали вставлять префиксы , отчего другие браузеры казались сломанными, когда, по факту, всё было выполнено по всем стандартам. Поэтому были введены некоторые такие функции.

Если вы собираетесь использовать подобные опции, проверьте совместимость их с браузерами.

Примечание: Пример с  смотрите на background-clip-text.html (или источнике).

Possible Values

Here’s an explanation of these values:

This keyword specifies that no drop shadow will be added to the element. If you use this keyword, there’s no need to add the other values.
<length>{2,4}

This can be either two values, three values, or four, as indicated below:

<horizontal-offset> (required)
Determines the horizontal offset of the drop shadow. It is a value. For example, or . Negative values are allowed. If a negative value is provided, the offset will result in the drop shadow being drawn to the left of the box. If it is a positive value, it will be drawn to the right.
<vertical-offset> (required)
Determines the vertical offset of the drop shadow. It is a value. For example, or . Negative values are allowed. If a negative value is provided, the offset will result in the drop shadow being drawn above the box. If it is a positive value, it will be drawn below.
<blur> (optional)
Determines the Gaussian blur effect (if any). It is a value. If the value is zero (i.e. ), the edge of the shadow will be sharp. The higher the value, the more blurred the shadow will become. Negative values are not allowed for a Gaussian blur.
<spread_distance> (optional)
Determines the size of the drop shadow. It is a value. Adding a positive value here will increase the size of the drop shadow — it will expand in all directions. A negative value will decrease the size (it will contract).
<color>? (optional)
Determines the color of the drop shadow. It can be any valid value. For example, , or are all valid colors. If this value isn’t provided, the value will be taken from the property.
This (optional) keyword specifies that the drop shadow will be added to the inside of the element, making it an «inner shadow». This can give the element the appearance being «cut out» of the canvas/page (as opposed to an «outer shadow» in which the element appears to be hovering above the page). If the keyword is omitted, the drop shadow will be an «outer shadow».

In addition, all CSS properties also accept the following CSS-wide keyword values as the sole component of their property value:

Represents the value specified as the property’s initial value.
Represents the computed value of the property on the element’s parent.
This value acts as either or , depending on whether the property is inherited or not. In other words, it sets all properties to their parent value if they are inheritable or to their initial value if not inheritable.

CSS-фигуры

Мы можем сделать обтекание содержимым непрямоугольных фигур, используя CSS-фигуры (en-US).

В примере ниже мы эффектно округлили воздушный шар. В действительности изображение прямоугольное, но с определением свойства float (по-другому формы не добавляются) и использованием свойства (en-US) со значением , мы можем создать эффект обтекания текста.

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

Примечание: В Firefox вы можете использовать Инспектор фигур, чтобы редактировать фигуры.

Значение  — лишь одно из нескольких базовых фигур для этого свойства, но можно и создавать формы. (Читайте Обзор CSS-фигур на MDN.)

Использование нескольких теней одновременно

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

PHP

box-shadow: 10px 0px 5px -5px #555,
-10px 0px 5px -5px #555,
0px 10px 5px -10px #555,
inset 0px 0px 2px;

1
2
3
4

box-shadow10px0px5px-5px#555,

-10px0px5px-5px#555,

0px10px5px-10px#555,

inset0px0px2px;

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

Вот как это выглядит:

Сложная тень CSS3

Еще один момент! Так как свойство box-shadow относится к разряду свойств CSS3, то оно может не поддерживаться более старыми версиями браузеров, поэтому если вам нужно сделать коссбраузерную верстку с поддержкой теней, то свойство box-shadow нужно задавать для каждого браузера со специальными кроссбраузерными префиксами:

PHP

-webkit-box-shadow: 10px 0px 5px -5px #555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;
-moz-box-shadow: 10px 0px 5px -5px #555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;
-o-box-shadow: 10px 0px 5px -5px #555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;
-ms-box-shadow: 10px 0px 5px -5px #555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;

1
2
3
4

-webkit-box-shadow10px0px5px-5px#555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;

-moz-box-shadow10px0px5px-5px#555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;

-o-box-shadow10px0px5px-5px#555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;

-ms-box-shadow10px0px5px-5px#555, -10px 0px 5px -5px #555,0px 10px 5px -10px #555, inset 0px 0px 2px;

-webkit – для вебкит браузеров (Яндекс-браузер, GoogleChrome, новая версия Opera и т.д.)
-moz – для Mozilla Firefox
-о – для старых версий Opera
-ms — для Internet Explorer 8

Также должна вас предупредить, что даже использование кроссбраузерных префиксов не даст вам 100% гарантии отображения теней во всех старых браузерах.

Как видите, сделать с помощью CSS тень для блока не так уж и сложно. Главное понять какой параметр за что отвечает, и, подключив фантазию, вы сможете сделать очень интересное оформление для своего сайта. На мой взгляд, сайты с грамотно расставленными тенями для элементов выглядят очень красиво.

Так же, при помощи box-shadow можно сделать реалистичную тень блока CSS разной сложности, но для этого нужно использовать дополнительные приемы. Поэтому, созданием таких теней мы займемся в следующий раз.

С уважением Юлия Гусарь

Sintaxe

Especificando uma única box-shadow usando:

  • Dois, três ou quatro valores para .

    • Se apenas dois valores forem definidos, eles serão interpretados como valores de .
    • Se o terceiro valor for dados, é interpretado como .
    • Se o quarto valor for dados, é interpretado como .
  • Opcionalmente, o atributo .
  • Opcionalmente, o valor .

Para especificar mais de uma sombra, separe-as com virgula.

Se não for especificado, a sombra ganha o efeito de como se a caixa fosse aumentada acima do conteúdo).
A presença da palavra-chave muda a sombra para dentro da moldura (como se o conteúdo estivesse pressionado dentro da caixa). As sombras de inserção são desenhadas dentro da borda (mesmo as transparentes), acima do plano de fundo, mas abaixo do conteúdo.
Existem dois valores  (en-US)  para configurar o desvio (offset) da sombra:
 especifica a distância horizontal. Valores negativos colocarão a sombra à esquerda do elemento.
especifca a distância vertical. Valores negativos colocam a sombra acima do elemento.
Consulte  (en-US) para as unidades disponíveis.
Se ambos os valores forem , a sombra será posicionada atrás do elemento (e poderá gerar um efeito de desfocagem caso  e/ou  estiverem configurados).
Este é um terceiro valor para (en-US). Quanto maior for este valor, maior o efeito de desfocagem, desta forma a sombra se tornará maior e mais clara. Valores negativos não são permitidos. Se não for especificado, o valor padrão é  (os limites da sombra serão retos). A especificação não inclui um algoritmo exato de como o raio de esmaecimento deve ser calculado, no entanto, descreve o seguinte:
Este é um quarto valor de  (en-US). Valores positivos farão com que a sombra expanda e cresça maior, valores negativos farão com que a sombra encolha. Se não for especificado, o valor padrão é  (a sombra terá o mesmo tamanho do elemento)
Consulte  para possiveis palavras-chave e notações. Se não for especificada, a cor que será utilizada vai depender do navegador — geralmente é o valor da propriedade , mas tenha em mente que o Safari atualmente imprime uma sombra transparente neste caso.

Each shadow in the list (treating as a 0-length list) is interpolated via the color (as color) component, and x, y, blur, and (when appropriate) spread (as length) components. For each shadow, if both input shadows are or are not , then the interpolated shadow must match the input shadows in that regard. If any pair of input shadows has one and the other not , the entire shadow list is uninterpolable. If the lists of shadows have different lengths, then the shorter list is padded at the end with shadows whose color is , all lengths are , and whose (or not) matches the longer list.

none  

where

where

where

where

Тень внутри блока в CSS

Добиться эффекта появления тени внутри блока, можно прописав:

body{font-family: Arial,Verdana,sans-serif;}
h2{text-align: center;margin:5px 0 10px 0;font-weight:bold;}
p{font-size:0.8em;margin-bottom:5px;}
.bsh-wrap{width:300px; border:1px solid #f28cfb; border-radius:5px; margin:25px; overflow:hidden;}
.bsh-shad{position:relative;}
.bsh-shad:after {bottom: -1px; box-shadow: 0 0 8px 0 rgba(167, 97, 166, 0.8); content: ""; height: 1px; left: 1px; position: absolute; right: 1px;}
.bsh-inner{padding:10px;}

Можно добавить тень с одной или нескольких сторон блока:

boxShadow3 { 
width: 80%; 
max-width: 550px; 
margin: 1em auto; 
padding: 1em; 
box-shadow: 0 0 40px rgba(0, 0, 0, .1) inset;}
.boxShadow4 { 
width: 80%; 
max-width: 550px; 
margin: 2em auto; 
padding: 4em; 
background: lightcyan; 
box-shadow: 0 0 4em 4em white inset;}

Property Values

Value Description Play it
h-shadow Required. The position of the horizontal shadow. Negative values are allowed Play it »
v-shadow Required. The position of the vertical shadow. Negative values are allowed Play it »
blur-radius Optional. The blur radius. Default value is 0 Play it »
color Optional. The color of the shadow. Look at CSS Color Values for a complete list of possible color values Play it »
none Default value. No shadow Play it »
initial Sets this property to its default value. Read about initial Play it »
inherit Inherits this property from its parent element. Read about inherit

Tip: Read more about allowed values (CSS length units)

Compatibilidade com navegadores

Estamos convertendo nossos dados de compatibilidade para o formato JSON.
Esta tabela de compatibilidade ainda usa o formato antigo,
pois ainda não convertemos os dados que ela contém.
Descubra como você pode ajudar! (en-US)

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support 10.0
1.0-webkit (en-US)
(Yes) 4.0 (2.0)3.5 (1.9.1)-moz (en-US) 9.0 10.5 5.1
3.0 -webkit (en-US)
Multiple shadows 10.0
1.0-webkit (en-US)
(Yes) 4.0 (2.0)3.5 (1.9.1)-moz (en-US) 9.0 10.5 5.1
3.0 -webkit (en-US)
keyword 10.0
4.0-webkit (en-US)
(Yes) 4.0 (2.0)3.5 (1.9.1)-moz (en-US) 9.0 10.5 5.1
5.0 -webkit (en-US)
Spread radius 10.0
4.0-webkit (en-US)
(Yes) 4.0 (2.0)3.5 (1.9.1)-moz (en-US) 9.0 10.5 5.1
5.0 -webkit (en-US)
Feature Edge Safari Mobile Opera Mini Opera Mobile Android
Basic support (Yes)

5.0(Yes)-webkit (en-US)

? (Yes) (Yes)-webkit (en-US)
Multiple shadows (Yes) 5.0(Yes)-webkit (en-US) ? ? ?
keyword (Yes) 5.0(Yes)-webkit (en-US) ? ? ?
Spread radius (Yes) 5.0(Yes)-webkit (en-US) ? ? ?

Shadows affect layout in older Gecko, Presto, and WebKit; e.g. if you cast an outer shadow to a box with a of , you’ll see a scrollbar.

Since version 5.5, Internet Explorer supports Microsoft’s DropShadow and Shadow Filter. You can use this proprietary extension to cast a drop shadow (though the syntax and the effect are different from CSS3). In order to get in IE9 or later, you need to set (en-US) to .

Gecko 13 (Firefox 13 / Thunderbird 13 / SeaMonkey 2.10) removed support for . Since then, only the unprefixed version is supported. Shadows affect layout in older Gecko, Presto, and WebKit; e.g. if you cast an outer shadow to a box with a of , you’ll see a scrollbar.

In addition to the unprefixed support, Gecko 44.0 (Firefox 44.0 / Thunderbird 44.0 / SeaMonkey 2.41) added support for a prefixed version of the property for web compatibility reasons behind the preference , defaulting to . Since Gecko 49.0 (Firefox 49.0 / Thunderbird 49.0 / SeaMonkey 2.46) the preference defaults to .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector