Как работает box shadow css

box-shadow

Добавляет тень к элементу. Допускается использовать несколько теней, указывая их параметры через запятую, при наложении теней первая тень в списке будет выше, последняя ниже. Если для элемента задается радиус скругления через свойство border-radius , то тень также получится с закругленными уголками. Добавление тени увеличивает ширину элемента, поэтому возможно появление горизонтальной полосы прокрутки в браузере.

Синтаксис

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

Значения

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

HTML5 CSS3 IE Cr Op Sa Fx

Результат примера показан на рис. 1.

Вид тени в браузере Safari

Рис. 1. Вид тени в браузере Safari

Браузеры

Safari до версии 5.1, Chrome до версии 10.0, Android до версии 4.0 и iOS Safari до версии 5.0 поддерживают свойство -webkit-box-shadow .

Firefox до версии 4.0 поддерживает свойство -moz-box-shadow .

Internet Explorer до версии 9.0 не поддерживает свойство box-shadow , взамен можно использовать нестандартное свойство filter :

Здесь: offX &#8212; смещение тени по горизонтали; offY &#8212; смещение тени по вертикали; color &#8212; цвет тени.

Применение фильтра dropshadow дает четкую резкую тень, поэтому для эффекта размытия можно использовать фильтр shadow .

Здесь: direction &#8212; угол направления тени от 0 до 360°; color &#8212; цвет тени; strength &#8212; смещение тени в пикселах.

Box-shadow: тень для элемента

Вы можете добавлять к элементам тень и изменять ее внешний вид с помощью CSS-свойства box-shadow. Этот стиль позволяет воплотить в жизнь интересные эффекты, например, объемность и трехмерность блока. Свойство поддерживается всеми современными браузерами. Исключение составляют IE8 и Opera Mini.

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

Данный стиль записывается следующим образом:

Рассмотрим по порядку, за что отвечает каждый параметр (слева направо):

  • Ключевое слово inset : параметр, который необязательно указывать; рисует тень внутри элемента.
  • Сдвиг по оси X: указывает степень смещения тени по горизонтали относительно элемента. Положительное значение означает сдвиг вправо, отрицательное — влево. Значение 0 означает, что тень без сдвига.
  • Сдвиг по оси Y: указывает степень смещения тени по вертикали. Положительное значение означает сдвиг вниз, отрицательное — вверх. Значение 0 — это тень без сдвига.
  • Радиус размытия: это степень размытия тени. Чем больше значение, тем более размыта тень. Если параметр не указан, используется значение по умолчанию — 0 . В таком случае тень будет идеально четкой.
  • Расширение: необязательный параметр, отвечающий за растяжение тени по обеим осям; чем больше значение, тем больше растяжение. Расширение работает только при наличии предыдущего параметра. Значение по умолчанию — 0 .
  • Цвет тени: с этим параметром всё понятно — он задает цвет тени элемента. Цвет по умолчанию — черный.

Примечание. Браузерам Android и более старым версиям iPhone Safari требуется префикс -webkit- для корректной работы CSS свойства box-shadow.

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

Примеры box-shadow

Чтобы вы лучше поняли всю силу и прелесть свойства CSS box-shadow, мы покажем несколько примеров, которые можно смело применять на практике. Данное свойство способно сильно преобразить обычный блок!

Легкая тень

Эффект бумаги

Несколько слоев

Тройная рамка

Уголки

Как видите, свойство box-shadow предоставляет огромное поле для фантазии. Вы можете преображать блоки как угодно — главное, иметь чувство меры! &#128521;

В следующей главе вас ждет изучение свойств width и height, определяющих размеры элементов.

box-shadow

Take your JavaScript to the next level at Frontend Masters.

The box-shadow property in CSS is for putting shadows on elements (sometimes referred to as &#8220;drop shadows&#8221;, ala Photoshop/Figma).

  1. The horizontal offset (required) of the shadow, positive means the shadow will be on the right of the box, a negative offset will put the shadow on the left of the box.
  2. The vertical offset (required) of the shadow, a negative one means the box-shadow will be above the box, a positive one means the shadow will be below the box.
  3. The blur radius (required), if set to 0 the shadow will be sharp, the higher the number, the more blurred it will be, and the further out the shadow will extend. For instance a shadow with 5px of horizontal offset that also has a 5px blur radius will be 10px of total shadow.
  4. The spread radius (optional), positive values increase the size of the shadow, negative values decrease the size. Default is 0 (the shadow is same size as blur).
  5. Color (required) &#8211; takes any color value, like hex, named, rgba or hsla. If the color value is omitted, box shadows are drawn in the foreground color (text color ). But be aware, older WebKit browsers (pre Chrome 20 and Safari 6) ignore the rule when color is omitted.

Using a semi-transparent color like rgba(0, 0, 0, 0.4) is most common, and a nice effect, as it doesn&#8217;t completely/opaquely cover what it&#8217;s over, but allows what&#8217;s underneath to show through a bit, like a real shadow.

You use the inset keyword:

Here&#8217;s a snippet with vendor prefixes giving as deep of browser support as easily possible:

You can even get a box shadow to work in IE 8. You need an extra element, but it&#8217;s do-able with filter .

Using a negative spread radius, you can get squeeze in a box shadow and only push it off one edge of a box.

Multiple Borders & More

You can comma separate box-shadow any many times as you like. For instance, this shows two shadows with different positions and different colors on the same element:

The example shows how you can use that to create multiple borders:

By applying the shadows to pseudo elements which you then manipulate, you can get some pretty fancy 3D looking box shadows:

Comparison with filter: drop-shadow()

They can do similar things! But also, wait for it, different things. This is a deep dive article on this. Perhaps the biggest thing to know is that a filter will hug the edges of an element moreso than the rectangular box-shadow will do (even though box-shadow does hug rounded corners).

See snippet at top of page for specifics on vendor prefix coverage. This is one of those properties where dropping the prefixes is pretty reasonable at this point.

Frontend Masters logo

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Frontend Masters logo

Need front-end development training?

Frontend Masters is the best place to get it. They have courses on all the most important front-end technologies, from React to CSS, from Vue to D3, and beyond with Node.js and Full Stack.

Comments

Good to see this, But this is very basic.
I was looking for something advanced.

Anyways thanks for this!

Is there anything like outset, to counteract inset value (using LESS mixin and need to fill the variable set for inset).

HTML SCSS Result
.box <
box-shadow:
0 2.8px 2.2px rgba(0, 0, 0, 0.034),
0 6.7px 5.3px rgba(0, 0, 0, 0.048),
0 12.5px 10px rgba(0, 0, 0, 0.06),
0 22.3px 17.9px rgba(0, 0, 0, 0.072),
0 41.8px 33.4px rgba(0, 0, 0, 0.086),
0 100px 80px rgba(0, 0, 0, 0.12)
;

min-height: 200px;
width: 50vw;
margin: 100px auto;
background: white;
border-radius: 5px;
>

body <
background: #EEF2F7;
>

Hi, first i must say i love you site and it has helped me many times.
one thing about box shadow i am see is that there is a difference between FF and chrome in terms of the distance.
what i mean is, when useing this code

in FF it shows a nice shadow on the bottom of the box, but in chrome it is not showing. in order to show i need to change it to this:

would love to hear what you say about this.
Thanks

i like css3 and your site 🙂 but i hate INTERNET EXPLORER :@

Here is a test page for comparison. View this page in Chrome, IE, then FireFox (current versions).

Notice that Chrome and IE (wow!) display it correctly, while FireFox does not render the same way.

Here is the css:

td.greybutton:hover <
background: #944F1B;

Here is the markup:

Any ideas on how to get FireFox to play nice?

BTW &#8211; Safari seems fine too, but Opera renders similarly to FireFox.

could you post the code to make Effect 2, I cant figure it out nor understand what you meant by pseudo elements?

Ok, so I feel like a dufus lol. found where the html and css was lol. But I tried it and it doesnt do anything? I will play with it for a while maybe I am doing something wrong

Thank you very much for sharing, the effects are very cool.

In the rule for Effect 7 I don&#8217;t really understand how the code works:

Why does the subsequent skew and rotate change the shadow the way it does?

@Chris Coyier
Would you mind leaving a suggestion/compliment on my website @leftree.webs.com? Yes,I have used the Sitebuilder,but I have a pretty well knowledge of HTML5 & CSS3 as can be demonstrated here: http://www.codecademy.com/kerpoof/codebits/NsulFX/edit
How to:Just click on the green lightbulb on the bottom left corner.Thanks!

This page is way over the edge. See above, under &#8220;The example shows how you can use that to create multiple borders&#8221;&#8230; What an incredible HTML/CSS/PRIVIEW app. Granted, div is a hairy translation of the browser surface. But this is the first I&#8217;ve seen of this kind of thing. This is the stuff browser programmers look at in wonder (and pride). 10 years maybe and this inspiration surfaces in a literal DOM. So we can write this kind of content in plain English. Another good one, people! This post box has Write and Preview tabs that are also working faultlessly. We&#8217;ve all seen this site struggle. Today, you all shine. CSS-Tricks, amazing!

I&#8217;m trying to apply effect3 on my own div, but it doesn&#8217;t work,
PS : when i put my div outside of all the containers the effect works
Can you help me please!

The PlaceKitten image in your multiple borders example isn&#8217;t showing in my browsers (tested in Chrome and FF so far). However, after researching PlaceKitten, I discovered that adding a &#8220;g modifier&#8221; would display the greyscale version, and sure enough, when I inspected the image in Chrome and changed its source from http://placekitten.com/200/200 to http://placekitten.com/g/200/200, it showed up just fine. So, I presume there&#8217;s no color version of that image available.

Anyway, the article is quite useful and worthy of bookmarking.

When combined with bootstrap, bootstrap breaks the shadow, how could it be?

Hi there! Cool snippets on your site, thank you very much!

I have an issue with the shadow. As I put this values the page loads very slow and gets stuck on chrome. Are the values to high?

body <
-moz-box-shadow: inset 0 200px 430px #000000;
-webkit-box-shadow: inset 0 200px 430px #000000;
box-shadow: inset 0 200px 430px #000000;
>

Testing your rule locally in Chrome 40.0.2214.91 m on my Windows XP Professional desktop didn&#8217;t cause any issues. Could you provide a link to the problem page? There may be a conflict of some sort with other code there because the page in which I tested it had just the HTML5 boilerplate code found at http://csswizardry.com/2011/01/the-real-html5-boilerplate/.

Hi Wayne thank you very much for the testing and the replying. At the end I just took the shadows away. I am also happy that way; no need to look further. Here is the page: http://www.empiresofevil.tv
yes, cheers for you to!

I am using shadow effect 5 and I really like all the different shadow effects. But I cannot figure out to make my web page body a different color and keep the white color in my wrapper. When I try to do this I lose the shadow completely. I have tried adding a z-index to my wrapper but that did not change anything. Any ideas or suggestions on how to do this would be greatly appreciated.

Here is my wrapper code for the wrapper&#8230;

.wrapper <
background-color: #ffffff;
color: #000000;
margin: 0 auto;
padding: 0;
text-align: left;
box-shadow: 0 0 30px rgba(0, 0, 0, 0.4);
>

I had the same issue, here&#8217;s what I did:

Get the parent container with bg color.
Give it &#8220;position: relative&#8221; and &#8220;z-index: -1&#8221;

That worked for me.

Multiple borders .. I really like that one

Very good, thank you

Hello people from earth, I am from another world. but I want to learn html an css =P
my question is about the effect 2, Is it possible to do that with a youtube videoplayer, Thanks in advances! xD

hi I&#8217;m using this code on my site to highlight images on hover, but some of the boxes are not showing correctly. Maybe because they are different sizes??

here&#8217;s the code I&#8217;m using,

and here&#8217;s the rest of the code&#8230; its doing exactly what i want when its a square box. If can get it to work on anysize box, that would be great

Is there an easy way to make the shadow conform to the size of the box&#8230; this is probably happening because if have a hard coded with, and when the box is a different size maybe the shadow isnt working&#8230; please hover on

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

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