Have you ever had an unpleasant feeling when your captions didn't match the colors of buttons, panels, or simply the text contrasted poorly with the background of the page? By using CSS shadows This problem can be easily solved by using the text-shadow property to improve the readability and contrast of the text.

In the examples given, we use text shadows in various situations, which will give you the necessary basis so that you can further study this issue on your own.

1. Basic setup

Create a new one HTML file and add the following code to it HTML And CSS:




CSS Buttons






In the HTML section, add a tag

with the text class:


Web Code Geeks

For this element we will add a shadow CSS text. I set initial properties for this element so that it looks nice on the screen:


Now let's set the text-shadow attribute to the text. But first, let's figure out what values ​​this attribute takes:

Text-shadow: 4px 4px 4px #ccc;

  1. 4px - X offset ( horizontal);
  2. 3px - Y axis offset ( vertical);
  3. 2px - blur value;
  4. #ccc - color.

This is set as follows:

Text-shadow: horizontal-offset vertical-offset blur color;

de color can be represented by hexadecimal code #ccc or RGBA (0,0,0,0.3); . In CSS, we can apply a CSS inner shadow to our text like this:


.text(
font-size: 5em; /* make the text larger */
text-shadow: 4px 3px 2px #ccc;
}

The browser representation of this shadowed text would look like this:

EXAMPLE website

Next we will change the background color of the body element in different ways. We do this because some CSS shadows require a specific background, otherwise they won't be noticeable. To make the text look more beautiful, we will set it in upper case.

2. Imprint effect

Set the text color to a slightly darker shade than the background. Then apply a small white text shadow with the opacity reduced:

Body (
background: #222;
}
.text(
font-size: 5em;
color: rgba(0,0,0,0.6); /* text color */
text-shadow: 2px 2px 3px rgba(255,255,255,0.1); /* adding a shadow */
}

Using the RGBA code you can set the opacity of the color. Notice that the text color has an opacity of 60% (0.6) and the div CSS shadows have an opacity of 10% (0.1).

EXAMPLE website

3. Retro shadow effect

Retro shadows don't always need to be blurred. Take this retro shadow for example:

Body (
}
.text(
font-size: 5em;
color: white; /* change the text color to white */
text-shadow: 6px 6px 0px rgba(0,0,0,0.2); /* adding retro shadow */
}

EXAMPLE website

4. Double shadow effect

Interestingly, you can add more than one CSS font shadow. This can be done like this: text-shadow: shadow1, shadow2, shadow3; Let's add two shadows, one with the background color and the second a little darker:

Text(
font-size: 5em;
text-shadow: 4px 3px 0px #fff, 9px 8px 0px rgba(0,0,0,0.15); /* gives two shadows */
}

Our background is white, so we don't need another color for it. In the browser the effect will look like this:

EXAMPLE website

5. Remote shadow effect

This effect is based on the function of detecting several beautiful shadows CSS. Below you can see the effect with four shadows cast downwards at varying degrees of intensity:

Body (
background: #fff3cd; /* change the background color */
}
.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);
}

EXAMPLE website

6. 3D effect by Mark Dotto

Body (
background: #3495c0; /* change the background color */
}
.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);
}

Now see how these CSS inner text shadows look in the browser:

EXAMPLE website

7. Realistic Gordon Hall Cut Text Effect

Gordon uses some advanced CSS magic to give not only an outer shadow, but also a realistic inner shadow:

Body (
background: #cbcbcb; /* change the background color */
}
.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;
}

And this creates the effect of cut text.

EXAMPLE website

8. Text glow effect

body(
background: #992d23; /* change the background color */
}
.text(
font-size: 5em;
color: white;
text-shadow: 0px 0px 6px rgba(255,255,255,0.7);
}

This shadow creates a glowing effect for the text:

EXAMPLE website

9. Raised Text Effect

body(
background: #629552; /* change the background color */
}
.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);
}

EXAMPLE website

10. Long shadow effect

This effect can be done using

Background-color: rgb(147, 201, 67);
text-shadow: 1px 1px rgb(131, 179, 60), 2px 2px rgb(131, 179, 60), 3px 3px rgb(131, 179, 60), 4px 4px rgb(131, 179, 60), 5px 5px rgb(131, 179, 60), 6px 6px rgb(131, 179, 60), 7px 7px rgb(131, 179, 60), 8px 8px rgb(131, 179, 60), 9px 9px rgb(131, 179, 60), 10px 10px rgb(131, 179, 60), 11px 11px rgb(131, 179, 60), 12px 12px rgb(131, 179, 60), 13px 13px rgb(131, 179, 60), 14px 14px rgb (131, 179, 60), 15px 15px rgb(131, 179, 60), 16px 16px rgb(131, 179, 60), 17px 17px rgb(131, 179, 60), 18px 18px rgb(131, 179, 60 ), 19px 19px rgb(131, 179, 60), 20px 20px rgb(131, 179, 60), 21px 21px rgb(131, 179, 60), 22px 22px rgb(131, 179, 60), 23px 23px rgb( 131, 179, 60), 24px 24px rgb(131, 179, 60), 25px 25px rgb(131, 179, 60), 26px 26px rgb(131, 179, 60), 27px 27px rgb(131, 179, 60) ;
color: #eaeaea;

EXAMPLE website

Conclusion

As you can see, the text-shadow property is very easy to use and you can use it to create your own creative CSS shadows.

Even the greenest designer knows how to make shadows in Photoshop. Shadows add dimension to the design and are now very popular. Shadows for texts, menu items and headings are no exception. Suffice it to recall the design of interfaces from apple

It will be useful to have skills in working with text shadows in your arsenal of techniques.

Task

Make a shadow for text using CSS, without using images. What will we achieve with this?

  • flexibility - no images required, text is easy to change
  • speed - fewer images - less page weight, fewer calls to the server
  • SEO - text is optimized better than pictures, and is more reliable than using the technique of replacing text with a picture

Text shadows for normal browsers

All were included in normal browsers modern browsers, which are more or less in step with the W3C recommendations. In this case, these browsers understand the CSS3 text-shadow property, which was recommended back in 2003.

So, here is a list of browsers that support the text-shadow property:

  • Safari 3.1 (Mac/Win) - supports, does not support multiple shadows
  • Safari 4 (Mac/Win) - fully supported
  • Opera 9.5+ (Mac/Win/Lin) - fully supports
  • Firefox 3.1/3.5 (Mac/Win/Lin) - fully supports
  • Google Chrome 2 (Win) - fully supports
  • Shiira (Mac) - supports, does not support multiple shadows
  • Konqueror (Lin/Mac/Win) - fully supports
  • iCab (Mac) - supports, does not support multiple shadows
  • Safari on iPhone - supported, multiple shadows not supported
  • Nokia Symbian-Smartphones (Series 60) - supports
  • Opera Mini 4.1 - supports, does not support shadow blur

For these browsers, one line of CSS is enough to shadow text:

H1 ( text-shadow: 0px 1px 3px #000; )

We get this fancy headline:

You can achieve a variety of interesting effects with text-shadow.

Blurred text

H1 ( color: #fff; background: #666; text-shadow: 0px 0px 3px #fff; )

Duplicate text

H1 ( text-shadow: 0px 20px #000; )

Multiple shadows allow you to achieve several more effects:

Recessed text

H1 ( background: #ccc; color: #ccc; text-shadow: -1px -1px #666, 1px 1px #FFF; font-family: serif; )

Raised text

H1 ( background: #999; color: #999; text-shadow: 1px 1px 3px #666, -1px -1px 3px #FFF, 1px 1px #666, -1px -1px #FFF; font-family: serif; )

(IE will not allow you to enjoy the beauty here, because it does not support text-shadow). You can come up with a lot of different effects using text-shadow, the only practical limitation is your imagination.

Now about the sad thing - what to do with everyone’s “favorite” IE?

Text shadows in IE

Although IE up to version 8 does not understand text-shadow, it has plenty of its own “bells and whistles”. In particular, there is a dropShadow() filter for creating shadows. For shadows to appear, the element must have a layout set. You can install in several ways:

  • by setting the element properties: block + height() or width())
  • giving the element : absolute
  • by specifying: left/right
  • setting zoom: 1

H1 ( filter:progid:DXImageTransform.Microsoft.DropShadow(color="#666666",offX=2,offY=2,positive="true"); zoom: 1; )

It seemed that one could shout “Hurray!!!” and enjoy life, but look how this filter works in reality:

This is how the text will appear if you apply the dropShadow filter to it

For those who do not understand, here are the disadvantages of this filter:

  • the shadow looks terrible: angular, no smooth transition into the background with translucency
  • font style is distorted
  • the shadow is practically impossible to adjust (you can only control the position of the shadow) - this can be partially circumvented by using the shadow filter instead of dropShadow, but the critical first two drawbacks remain
  • the mandatory presence of a layout somewhat limits the developer

This result is not acceptable in real projects. It is unclear who and how took over such work from the developers.

Kilian Valkhof suggested using shadow emulation:

  1. do not apply the filter directly to the text
  2. use a combination of glow and blur filters instead of dropShadow and shadow

This will avoid text distortion and make the shadow more flexible.

Test headerТестовый заголовок

H1 ( text-shadow: 3px 3px 3px #cccccc; position: relative; zoom: 1; color: #000; ) h1 span ( position: absolute; left: -3px; top: -3px; z-index: -1; filter: progid:DXImageTransform.Microsoft.Glow(Color=#cccccc,Strength=1) progid:DXImageTransform.Microsoft.blur(pixelradius=3, enabled="true" ; zoom: 1;

But even with this approach, there are still a number of disadvantages:

  • non-semantic code is an extra element, and even with duplication of text it will not have the best effect on the logical structure of the content, SEO optimization. This problem can be solved with using javascript which will insert an extra element for IE when the page loads
  • does not correspond to the display in other browsers (which understand text-shadow) - filters allow you to emulate a shadow with minimal settings. It is not always possible to achieve shadow similarity with other browsers
  • less flexibility - filters will not provide all the possibilities of text-shadow, for example, it will not be possible to implement multiple shadows

To create shadows for IE, you can use javascript (not the first time javascript has saved the day)

Text shadows using javascript

From the scripts that I tested, I chose the jquery plugin "Drop Shadow". Its advantages:

  • emulates shadows by inserting multiple containers, i.e. without using filters for IE. This makes it possible to make shadows in IE as similar as possible to other browsers + no need to worry about layout for IE
  • creates shadows not only for IE, which can sometimes be useful
  • the script is lightweight - 4Kb (if you remove comments from the code), and if you apply compression, it will be even less. There are requirements in writing a script - the presence of the jquery.dimensions.js script, but I still don’t understand why it is needed. Shadows are created, deleted, defined by id and without it.
  • simple and clear to use
  • You can emulate multiple shadows with some success

Flaws:

  • you cannot initialize a script by element id
  • if the element is given a background, the shadow will be created not for the text, but for the element as a whole
  • mandatory connection jquery libraries(and this is more than 50Kb). But the popularity of jquery practically eliminates this drawback
  • According to the script description, the connection of jquery.dimensions.js (another 2Kb) is also required. But I don’t understand why this library is needed, everything seems to work fine without it

Using the Drop Shadow plugin

Syntax:

JQuery(selector).dropShadow(options); // creating a shadow on the element jQuery(selector).redrawShadow(); // redrawing the shadow jQuery(selector).removeShadow(); // removing the shadow jQuery(selector).shadowId(); // returns the id of the element's shadow

Left: [integer] (default = 4) top: [integer] (default = 4) blur: [integer] (default = 2) opacity: [fractional number] (default = 0.5) color: [string] (default = "black") swap: [boolean] (default = false)

The left and top parameters are the coordinates of the beginning of the shadow relative to the upper left corner of the label (or object). Positive values ​​move the shadow to the right and down, negative values ​​move the shadow to the left and up.

Vlad Merzhevich

At one time there was a certain fashion for text with shadows and a similar effect could be found on almost any website. IN graphic editor The shadow is added simply, it looks great, here is the text with a shadow and shoved onto the web page, regardless of the style of the site and the designer’s sense of proportion. When most browsers began to support the text-shadow style property, the fashion had already passed and now text with a shadow is quite rare. However, text-shadow has a number of other implicit uses that few people suspect. Using this property, you can create outline text, “extrude” it, create a glow, blur, and much more.

Using text-shadow

Four parameters are written as values: shadow color, horizontal and vertical displacement, and shadow blur radius (Fig. 1).

Rice. 1. Text-shadow parameters

Color can be written at the beginning or end of all parameters in any suitable CSS format. So you can make a translucent shadow through rgba format. Positive offset values ​​cast the shadow to the right and down, while negative offset values ​​cast the shadow to the left and up, respectively. To have a shadow around the text, just set the offset values ​​to zero. The blur radius sets how sharp the shadow will be. The larger the blur radius, the softer the shadow looks.

A big advantage of text-shadow is the ability to add several different shadows at once, listing their parameters separated by commas. This feature basically allows you to create different effects.

Unfortunately, IE before version 10.0 does not support text-shadow , so we won’t see any beauty in this browser.

Outline text is characterized by the fact that each letter is surrounded by a line, the color of which differs from the color of the text (Fig. 2). This effect looks best with large font size, such as headings. For body text, using an outline only impairs readability.

Rice. 2. Outline text

A contour can be created using two methods. In the first method, we set a zero shadow offset and a small blur radius, literally 1-2 pixels (example 1). Increasing the blur value turns the outline into a glow around the text, which is a different effect.

Example 1: Outline text

Text

Outline text

The contour made by this method is shown in Fig. 1. The outline turns out to be slightly blurred, so for those who want to get a clear line, the second method is intended. It consists of using four sharp shadows of the same color, they are shifted to different angles by one pixel (example 2).

Example 2. Four shadows for the outline

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

Outline text

The appearance of such a contour is shown in Fig. 3. It is noticeable that the contour is more expressive.

Rice. 3. Contour with four shadows

To add the 3D text effect shown in Fig. 4, several shadows are applied simultaneously, which are shifted relative to each other by one pixel horizontally and vertically.

Rice. 4. 3D text

Personally, this type of text reminds me of retro style lettering and, again, it is best suited for headings, rather than the body of a web page.

The number of shadows depends on how much you want to “pull” the text forward. A larger number increases the “depth” of the letters, a smaller number, on the contrary, reduces the three-dimensionality. Example 3 uses five shadows of the same color.

Example 3: Shadow to add three-dimensionality

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

Ten chamber refrigerator

For all shadows we set the blur radius to zero and the same color. The shadows differ only in their offset values.

Text embossing

To create the effect of text embossing or, in other words, relief, the color of the text must match the background color. One part of the letters “protruding” above the surface seems to be illuminated, while the other part is in the shadow (Fig. 5).

Rice. 5. Embossed text

To add a similar effect, we need two shadows - we move the white shadow up to the left by one pixel, and the dark gray one down to the right (example 4).

Example 4: Embossed text

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

Embossed text

The relief looks best on a gray background, so the effect is not suitable for every color scheme of the site. By the way, it’s easy to get pressed rather than extruded text; just swap the shadow colors.

Text-shadow: #333 -1px -1px 0, #fff 1px 1px 0;

Glow

The glow around the text is the same shadow, only it is bright and contrasting. Thus, to create a glow effect, just change the shadow color and set the desired blur radius. Since the glow around the text should be uniform, the shadow offset should be set to zero. In Fig. Figure 6 shows an example of glowing in different colors.

Rice. 6. Glow text

Example 5. Glow

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

Bright side

Dark side

Blur

The shadow itself is blurred, so if we leave only the shadow and hide the text itself, we will get blurry letters (Fig. 7), and the degree of blur can be easily adjusted using the text-shadow parameter.

Rice. 7. Text with blur

To hide the original text, just set the color to transparent (example 6). The shadow color then acts as the text color, and the blur radius sets the degree of blurring of the letters.

Example 6: Blur text

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

Blurred text

Shadow and pseudo-classes

The shadow doesn't have to be added directly to the text; the text-shadow property plays nicely with the :hover and :first-letter pseudo-classes. Due to this, interesting effects are obtained with text, such as the contoured first letter of a paragraph or the glow of a link when hovering the mouse cursor over it. Example 7 shows such techniques.

Example 7: Using Pseudo-Classes

HTML5 CSS3 IE 9 IE 10+ Cr Op Sa Fx

Text

A niche project slows down the traditional channel, regardless of costs. The market structure, discarding the details, stabilizes the marketing and sales department, using the experience of previous campaigns. Brand building, of course, spontaneously pushes away convergent PR, winning a market segment. Investment synchronizes role social status, increasing competition. Brand naturally determines the placement plan, using the experience of previous campaigns.

The CSS text-shadow property is responsible for setting the shadow of the text. Very similar to the box-shadow property.

CSS text-shadow syntax

text-shadow : X Y R color ;
  • X - shift of the shadow relative to the text along the X axis (most often set in px pixels);
  • Y - shift of the shadow relative to the text along the Y axis (most often set in px pixels);
  • R - shadow radius (most often specified in px pixels);
  • color - color (can be specified in any format, see html color names)

The text-shadow syntax allows multiple shadows to be specified, separated by commas. For example

text-shadow : X1 Y1 R1 color1 , X2 Y2 R2 color2 , ...;

The shadow priority (which is higher, which is lower) depends on the specific CSS version. In CSS3, the first shadow in the list is placed at the very top, the last in the list is placed at the very bottom. In CSS2 it's the opposite.

Examples: how to make a shadow for text in html

Example No. 1. Simple shadow for text in html

Below is the simplest example with a text shadow. Here we have applied both offsets (X and Y) and also made a blur radius.

Текст с тенью

Текст с тенью

Пример №2. Фиксированная или жесткая тень у текста в html

Ниже представлены два примера. Тень в обоих случаях одинаковая (фиксированная), т.е. без размытия. Обратите внимание, какой эффект создается, если текст будет на черном фоне.

Фиксированная или жесткая тень
Фиксированная или жесткая тень с фоном

На странице преобразуется в следующее

Фиксированная или жесткая тень

Фиксированная или жесткая тень с фоном

Пример №3. Двойная тень у текста в html

Двойная тень

На странице преобразуется в следующее

Двойная тень

Пример №4. Вдавленные буквы у текста в html

Вдавленные буквы - вариант 1
Вдавленные буквы - вариант 2

На странице преобразуется в следующее

Вдавленные буквы - вариант 1

Вдавленные буквы - вариант 2

Пример №5. Вдавленные буквы у текста в html

Небольшой 3D текст

На странице преобразуется в следующее

Небольшой 3D текст

Для обращения к margin из JavaScript нужно писать следующую конструкцию:

document.getElementById("elementID").style.margin ="VALUE "

Описание

Добавляет тень к тексту, а также устанавливает её параметры: цвет тени, смещение относительно надписи и радиус размытия. Свойство text-shadow может работать совместно с псевдоэлементами :first-letter и :first-line .

Синтаксис

text-shadow: none | тень [,тень]*
где тень:
<сдвиг по x> <сдвиг по y> <радиус размытия> <цвет>

Значения

None Отменяет добавление тени. цвет Цвет тени в любом доступном CSS формате. По умолчанию цвет тени совпадает с цветом текста. Необязательный параметр. сдвиг по x Смещение тени по горизонтали относительно текста. Положительное значение этого параметра задает сдвиг тени вправо, отрицательное - влево. Обязательный параметр. сдвиг по y Смещение тени по вертикали относительно текста. Также допустимо использовать отрицательное значение, которое поднимает тень выше текста. Обязательный параметр. радиус Задает радиус размытия тени. Чем больше это значение, тем сильнее тень сглаживается, становится шире и светлее. Если этот параметр не задан, по умолчанию устанавливается равным 0. Учтите, что алгоритм сглаживания в браузерах обычно разный, поэтому вид тени может несколько различаться в зависимости от заданных параметров сглаживания.

Допускается указывать несколько параметров тени, разделяя их между собой запятой. В CSS3 учитывается следующий порядок: первая тень в списке размещается на самом верху, последняя в списке - в самом низу. В CSS2 порядок наоборот: первая тень размещается в самом низу, а последняя на самом верху.

HTML5 CSS2.1 CSS3 IE Cr Op Sa Fx

text-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. Shadow view in Safari browser

Browsers

Opera supports a maximum of 6–9 shadow options. Increasing this value, as well as increasing the blur radius above 100px, affects browser performance. Opera versions 9.5–10 use multi-shadow display similar to CSS2.

Safari before version 4.0 only supports one shadow option, the rest are ignored. Since version 4.0, many shadows are already working.

Browser Internet Explorer understands the text-shadow property only since version 10.0. Instead, the filter property is used: Shadow(parameters) . For example, the following construct specifies the color of the shadow (#666666), its direction (45° from vertical) and the offset amount (4 pixels).

filter: Shadow(Color=#666666, Direction=45, Strength=4);


Close