Css3. работа с тенями. часть 2

Содержание:

Make Your Webpage Elegant With CSS

By using CSS you have full control over the styling of your webpage. You can customize every HTML element using various CSS properties. Devs from all over the world are contributing to CSS updates, and they’ve been doing so since its release in 1996. As such, beginners have a lot to learn!

Luckily, CSS is beginner-friendly. You can get some excellent practice in by starting with a few simple commands and seeing where your creativity takes you.

10 Simple CSS Code Examples You Can Learn in 10 Minutes

Need help with CSS? Try these basic CSS code examples to start with, then apply them to your own web pages.

Read Next

About The Author

Yuvraj Chandra
(60 Articles Published)

Yuvraj is a Computer Science undergraduate student at the University of Delhi, India. He’s passionate about Full Stack Web Development. When he’s not writing, he’s exploring the depth of different technologies.

More
From Yuvraj Chandra

Syntax

/* 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;

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 keyword changes the shadow to one inside the frame (as if the content was depressed inside the box). Inset shadows are drawn inside the border (even transparent ones), above the background, but below content.
These are two values to set the shadow offset. specifies the horizontal distance. Negative values place the shadow to the left of the element. specifies the vertical distance. Negative values place the shadow above the element. See for possible units.
If both values are , the shadow is placed behind the element (and may generate a blur effect if and/or is set).
This is a third value. The larger this value, the bigger the blur, so the shadow becomes bigger and lighter. Negative values are not allowed. If not specified, it will be (the shadow’s edge is sharp). The specification does not include an exact algorithm for how the blur radius should be calculated, however, it does elaborate as follows:
This is a fourth value. Positive values will cause the shadow to expand and grow bigger, negative values will cause the shadow to shrink. If not specified, it will be (the shadow will be the same size as the element).
See values for possible keywords and notations.
If not specified, the color used depends on the browser — it is usually the value of the property, but note that Safari currently paints a transparent shadow in this case.

Interpolation

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.

Тень внутри блока в 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;}

Syntax

Falls nicht angegeben (Standardwert), wird angenommen, dass der Schatten ein Schlagschatten ist (als ob die Box über dem Inhalt schweben würde).
Die Angabe des Schlüsselworts ändert den Schatten so, dass er innerhalb des Rahmens angezeigt wird (als ob der Inhalt innerhalb der Box nach innen gedrückt wäre). Innere Schatten werden innerhalb des Randes (sogar transparenten) gezeichnet, über dem Hintergrund aber unterhalb des Inhalts.
Diese zwei -Werte setzen den Schattenabstand. beschreibt die horizontale Distanz. Negative Werte platzieren den Schatten links des Elements. beschreibt die vertikale Distanz. Negative Werte platzieren den Schatten oberhalb des Elements. Siehe für mögliche Einheiten.
Falls beide Werte sind, wird der Schatten hinter dem Element platziert (und können einen Unschärfeeffekt erzeugen, falls und/oder gesetzt sind).
Dies ist ein dritter -Wert. Je größer dieser Wert ist, desto größer ist die Unschärfe, sodass der Schatten größer und schwächer wird. Negative Werte sind nicht erlaubt. Falls nicht angegeben, ist der Wert (der Rand des Schattens wird scharf dargestellt).
Dies ist ein vierter -Wert. Positive Werte erweitern den Schatten und machen ihn größer, negative Werte verkleinern den Schatten. Falls nicht angegeben, ist der Wert (der Schatten hat die gleiche Größe wie das Element).
Siehe -Werte für mögliche Schlüsselwörter und Notationen.
Falls nicht angegeben, hängt die Farbe vom Browser ab – sie ist normalerweise der Wert der -Eigenschaft, aber Safari zeichnet in diesem Fall aktuell einen transparenten Schatten.

Jeder Schatten innerhalb der Liste ( wird als eine leere Liste interpretiert) wird über die Farbkomponente (als Farbe) interpoliert und x-, y-, Unschärfe- und (falls zutreffend) Ausbreitungskomponenten (als Länge). Für jeden Schatten gilt, falls beide angegebenen Schatten sind oder nicht, muss der interpolierte Schatten diesbezüglich mit den angegebenen Schatten übereinstimmen. Falls ein Schatten eines beliebigen Paares von angegebenen Schatten ist und der andere nicht, ist die gesamte Schattenliste nicht interpolierbar. Falls die Listen von Schatten verschiedene Längen haben, wird die kürzere Liste mit Schatten aufgefüllt, deren Farbe ist, alle Längen und dessen (oder nicht) mit dem der längeren Liste übereinstimmt.

none  

wobei

wobei

wobei

wobei

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)

Как сделать тень блока с помощью свойства box-shadow

Поддержка браузерами

1. Синтаксис свойства box-shadow

Свойство box-shadow прикрепляет одну или несколько теней к блоку. Свойство принимает либо значение none, которое указывает на отсутствие теней, либо список теней через запятую, упорядоченный от начала к концу.

Каждая тень является отдельной тенью, представленной от 2 до 4-х значений длины, необязательным цветом и необязательным ключевым словом inset. Допустимые длины ; опущенные цвета по умолчанию равны значению свойства color.

Свойство не наследуется.

Рис. 1. Синтаксис свойства box-shadow

box-shadow
Значения:
x-offset Задает горизонтальное смещение тени. Положительное значение рисует тень, смещенную вправо от текста, отрицательная длина — влево.
y-offset Задает вертикальное смещение тени. Положительное значение смещает тень вниз, отрицательное — вверх.
blur Задает радиус размытия. Отрицательные значения не допускаются. Если значение размытия равно нулю, то край тени четкий. В противном случае, чем больше значение, тем больше размыт край тени.
растяжение Задает расстояние, на которое тень увеличивается. Положительные значения заставляют тень расширяться во всех направлениях на указанный радиус. Отрицательные значения заставляют тень сжиматься. Для внутренних теней расширение тени означает сжатие формы периметра тени.
цвет Задает цвет тени. Если цвет отсутствует, используемый цвет берется из свойства color. Для Safari цвет тени указывать обязательно.
inset Изменяет отбрасываемую тень блока с внешней тени на внутреннюю.
none Значение по умолчанию, означает отсутствие тени.
initial Устанавливает значение свойства в значение по умолчанию.
inherit Наследует значение свойства от родительского элемента.

Эффекты тени применяются следующим образом: первая тень находится сверху, а остальные — сзади. Тени не влияют на компоновку и могут перекрывать другие элементы или их тени. С точки зрения контекстов укладки и порядка рисования внешние тени элемента рисуются непосредственно под фоном этого элемента, а внутренние тени элемента рисуются непосредственно над фоном этого элемента (ниже border и border-image, если таковые имеются).

Если элемент имеет несколько ящиков, все они получают тени, но тени рисуются только там, где также будут нарисованы границы; см. box-decoration-break.

Тени не вызывают прокрутку или не увеличивают размер прокручиваемой области.

2.3. Тень в стиле «материальный дизайн»

See the Pen YpypeE by Elena (@html5book) on CodePen.

По материалам

CSS3-оформление текста
CSS3-переходы

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

Ejemplos

En nuestro ejemplo, se incluyen tres sombras: una sombra interior, una sombra difuminada normal, y una sombra de 2px que crea un efecto de borde (podría haberse usado un en lugar de una tercera sombra).

Podrías dispararme con tus palabras,
podrías cortarme con tus ojos,
podrías matarme con tu odio,
y aún, como el aire, levantarme.
-Traduccion-

HTML

Cuando el , , y son todos cero, la sombra sera un contorno unifrome. Las sombras son dibujadas desde el fondo hasta el frente, así que la primera sombra se encuentra encima de sombras posteriores. Cuando el es 0, como por defecto, las esquinas de la sombra serán, bien, esquinas. De haberse definido un de cualquier otro valor, las esquinas habrían sido redondeadas.

Se ha añadido un margen del tamaño de la sombra más ancha para asegurarse de que la sombra no se superponga a los elementos adyacentes o vaya más allá del borde de la caja de contención. Una sombra de caja no afeta a las dimensiones del modelo de caja.

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

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

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 разной сложности, но для этого нужно использовать дополнительные приемы. Поэтому, созданием таких теней мы займемся в следующий раз.

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

Integrate CSS With an HTML Page

Now you know how to add cool box-shadow effects using CSS, you can easily integrate them with HTML elements in multiple ways.

You can embed it in the HTML page itself or attach it as a separate document. There are three ways to include CSS in an HTML document:

Internal CSS

Embedded or Internal Style Sheets are inserted within the <head> section of an HTML document using the <style> element. You can create any number of <style> elements in an HTML document, but they must be enclosed between the <head> and </head> tags. Here’s an example demonstrating how to use Internal CSS with an HTML document:

Inline CSS

Inline CSS is used to add unique style rules to an HTML element. It can be used with an HTML element via the style attribute. The style attribute contains CSS properties in the form of «property: value» separated by a semicolon (;).

All the CSS properties must be in one line i.e. there should be no line breaks between the CSS properties. Here’s an example demonstrating how to use inline CSS with an HTML document:

External CSS

External CSS is the most ideal way to apply styles to HTML documents. An external style sheet contains all the style rules in a separate document (.css file), this document is then linked to the HTML document using the <link> tag. This method is the best method for defining and applying styles to the HTML documents as the affected HTML file requires minimal changes in the markup. Here’s an example demonstrating how to use external CSS with an HTML document:

Create a new CSS file with the .css extension. Now add the following CSS code inside that file:

Lastly, create an HTML document and add the following code inside that document:

Note that the CSS file is linked with the HTML document via <link> tag and href attribute.

All the above three methods (Internal CSS, Inline CSS and External CSS) will display the same output-

Генераторы CSS-теней – эффективные решения

Для упрощения создания нужных эффектов существуют специальные CSS3-генераторы. Вот самые удобные и функциональные из них:

CSS3 Generator

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

CSS3Gen

Хороший генератор тени CSS, позволяющий создавать полезные фрагменты и с легкостью переносить их в свой проект. Этот CSS3-генератор позаботится обо всех префиксах для популярных браузеров:

CSS3 Please

Отличный вариант для тестирования CSS3-кода: с помощью редактора вносите изменения в CSS-стили, и блок мгновенно изменится, а вы сможете увидеть результат:

Удачной работы!

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 .

Примеры

Пример

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

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

Эффект ретро-тени

Для ретро-тени не всегда нужно применять размытие.

Возьмем, к примеру, эту ретро-тень:

body {
	background: #fff3cd;		/* изменяем цвет фона */
}

.text {
	font-size: 5em; 					
	color: white;		/* изменяем цвет текста на белый */
    text-shadow: 6px 6px 0px rgba(0,0,0,0.2);	/* добавление ретро-тени */
}

Эффект ретро-тени

Эффект двойной тени

Интересно, что вы можете добавлять более одной CSS тени шрифта. Это можно сделать следующим образом: text-shadow: shadow1, shadow2, shadow3;

Давайте добавим две тени, одна — с цветом фона, а вторая немного темнее:

.text {
	font-size: 5em; 												
    text-shadow: 4px 3px 0px #fff, 9px 8px 0px rgba(0,0,0,0.15);    /* дает две тени */
}

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

Эффект двойной тени

Эффект удаленной тени

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

body {
	background: #fff3cd;			/* изменяем цвет фона */
}
.text {
	font-size: 5em;
	color: white; 												
    text-shadow: 0px 3px 0px #b2a98f,
             	 0px 14px 10px rgba(0,0,0,0.15),
             	 0px 24px 2px rgba(0,0,0,0.1),
            	 0px 34px 30px rgba(0,0,0,0.1);		
}

Эффект удаленной тени

3D-эффект Марка Дотто

Следующий эффект был опубликован на MarkDotto.com, в нем используется 12 отдельных теней, чтобы создать реалистичный 3D-эффект:

body {
	background: #3495c0;			/* изменяем цвет фона */
}

.text {
	font-size: 5em;
	color: white; 												
    text-shadow: 0 1px 0 #ccc, 
              0 2px 0 #c9c9c9,
              0 3px 0 #bbb,
              0 4px 0 #b9b9b9,
              0 5px 0 #aaa,
              0 6px 1px rgba(0,0,0,.1),
              0 0 5px rgba(0,0,0,.1),
              0 1px 3px rgba(0,0,0,.3),
              0 3px 5px rgba(0,0,0,.2),
              0 5px 10px rgba(0,0,0,.25),
              0 10px 10px rgba(0,0,0,.2),
              0 20px 20px rgba(0,0,0,.15);
}

Теперь посмотрите, как эти внутренние тени текста CSS выглядят в браузере:

3D-эффект тени

Реалистичный эффект вырезанного текста Гордона Холла

Гордон использует некоторую продвинутую магию CSS, чтобы задать не только внешнюю тень, но и реалистичную внутреннюю тень:

body {
	background: #cbcbcb;			/* изменяем цвет фона */
}

.text {
	font-size: 5em;
	color: transparent; 										
	background-color: #666666;
		   -webkit-background-clip: text;
		   -moz-background-clip: text;
		   background-clip: text;
		   text-shadow: rgba(255,255,255,0.5) 0px 3px 3px;
}

И это создает эффект вырезанного текста.

Эффект вырезанного текста

Эффект свечения текста

body {
	background: #992d23;			/* изменяем цвет фона */
}

.text {
	font-size: 5em;
	color: white; 												
	text-shadow: 0px 0px 6px rgba(255,255,255,0.7);
}

Эта тень создает эффект свечения текста:

Эффект свечения текста

Эффект выпуклого текста

body {
	background: #629552;			/* изменяем цвет фона */
}
.text {
	font-size: 5em;											
	color: rgba(0,0,0,0.6);
	text-shadow: 2px 8px 6px rgba(0,0,0,0.2),
                 0px -5px 35px rgba(255,255,255,0.3);
}

Эффект выпуклого текста

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

Property Values

Value Description Play it
none Default value. No shadow is displayed Play it »
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
Play it »
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
Play it »
blur Optional. The blur radius. The higher the number, the more blurred the
shadow will be
Play it »
spread Optional. The spread radius. A positive value increases the size of the
shadow, a negative value decreases the size of the shadow
Play it »
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.Note: In Safari (on PC) the color parameter is required. If you do not specify the color, the shadow is not displayed at all. Play it »
inset Optional. Changes the shadow from an outer shadow (outset) to an inner 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)

Syntaxe

La propriété peut être définie grâce :

  • À deux, trois ou quatre valeurs de longueur () :
    • Avec deux valeurs, celles-ci sont respectivement considérées comme les coordonnées de décalage de l’ombre :
    • Si une troisième valeur est fournie, celle-ci correspondra au rayon du flou :
    • Si une quatrième valeur est fournie, celle-ci correspondra au rayon d’étalement : .
  • Au mot-clé optionnel
  • À une valeur de couleur () optionnelle.
Si la valeur n’est pas définie (le cas par défaut), l’ombre sera une ombre portée (comme si la boîte était élevée au-dessus du contenu).
La présence du mot-clé modifie l’ombre afin qu’elle soit tournée vers l’intérieur du cadre (comme si le contenu était enfoncé dans la boîte). Les ombres tournées vers l’intérieur sont dessinées à l’intérieur de la bordure (même les transparentes), au-dessus de l’arrière-plan mais sous le contenu.
Deux valeurs de longueur ( qui permettent de définir le décalage de l’ombre. définit la distance horizontale du décalage et les valeurs négatives placeront l’ombre à gauche de l’élément. définit la distance verticale et les distances négatives placent l’ombre au-dessus de l’élément (cf. pour les différentes unités possibles).
Si les deux valeurs sont , l’ombre est placée derrière l’élément (et peut générer un effet de flou si et/ou est utilisé).
Une troisième valeur de longueur (). Plus cette valeur sera grande, plus le flou de l’ombre sera diffus : l’ombre sera donc plus étalée et plus légère. Les valeurs négatives ne sont pas autorisées. Si la valeur n’est pas définie, sa valeur par défaut est (le côté de l’ombre est rectiligne).
Une quatrième valeur de longueur (). Les valeurs positives étaleront l’ombre et les valeurs négatives rétréciront l’ombre. Si elle n’est pas définie, la valeur par défaut est (l’ombre aura la même taille que l’élément).
Une valeur de couleur (). Si la valeur n’est pas définie, la couleur utilisée dépend du navigateur ce sera généralement la propriété mais Safari affiche une ombre transparente.

Chaque ombre de la liste ( sera traitée comme une liste de longueur nulle) est interpolée via la couleur, le décalage horizontal et vertical, le rayon de flou et l’étalement (lorsque c’est pertinent). Pour chaque ombre, si les deux ombres sont ou ne sont pas , l’ombre interpolée doit respecter cette valeur. Si l’une des ombres a et l’autre non, la liste d’ombres ne peut pas être interpolée. Si les listes d’ombres ont des longueurs différentes, la liste la plus courte sera complétée à la fin avec des ombres dont la couleur est , toutes les longueurs valent et pour que la valeur corresponde à la plus longue liste.

none  

Вариации

Дальше мы будем по-разному изменять цвет фона элемента 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)

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

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

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