- box-shadow
- Интерактивный пример
- Синтаксис
- Значения
- Интерполяция
- Формальное определение
- Формальный синтаксис
- Примеры
- Добавление трёх теней
- HTML
- CSS
- Результат
- Использование нулевых значений для смещений и радиуса размытия
- HTML
- Set Box Shadow Only at Bottom in CSS
- Use the box-shadow Property to Set the Bottom Box Shadow in CSS
- ocean90 / box-shadow.html
- How to Set Box Shadow Only at Bottom in CSS?
- box-shadow CSS Property
- Syntax
- Conclusion
- About the author
- Anees Asghar
box-shadow
CSS-свойство box-shadow добавляет тень к элементу. Через запятую можно задать несколько теней. Тень описывается смещениями по оси X и Y относительно элемента, радиусом размытия и распространения, а также цветом.
Интерактивный пример
Свойство box-shadow включает отбрасывание тени от границ практически любого элемента. Если для элемента с тенью задан border-radius , то отбрасываемая тень также будет с закруглёнными углами. Порядок наложения нескольких теней такой же, что и у текстовых теней: первая указанная тень будет поверх остальных.
Генератор теней — интерактивный инструмент, позволяющий сгенерировать значение для box-shadow .
Синтаксис
/* Ключевые слова */ box-shadow: none; /* 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; /* Любое количество теней через запятую */ box-shadow: 3px 3px red, -1em 0 0.4em olive; /* Глобальные значения */ box-shadow: inherit; box-shadow: initial; box-shadow: revert; box-shadow: revert-layer; box-shadow: unset;
Каждая тень определяется следующим образом:
Для одновременного создания нескольких теней используйте список значений, разделённых запятыми.
Значения
Если не указано (по умолчанию), то тень будет отбрасываться от элемента (придавая эффект выпуклости блоку). Наличие ключевого слова inset отбрасывает тень внутри элемента (создавая эффект вдавленности блока). Внутренние тени начинаются с рамок элемента (даже если они прозрачные), над фоном элемента, но не под его содержимым.
…для длинного прямого края тени должен быть создан цветовой переход, равный длине расстояния размытия, который перпендикулярен и центрирован по краю тени. Переход начинается от указанного цвета тени в конечной точке радиуса внутри тени до полностью прозрачного цвета в конечной точке пределов радиуса.
Интерполяция
Каждая тень в списке ( none считается за пустой список) интерполируется через значения цвета x, y, радиуса размытия и (когда это допустимо) и радиуса расширения. Для каждой тени, если обе входные тени отмечены как inset или ни одна из них таковой не является, то интерполированная тень будет соответствовать входным теням. Если в любой паре входных теней одна из них является внутренней ( inset ), а другая нет, то список теней не интерполируется. Если количество теней отличается в разных списках, то более короткий список дополняется в конце тенями, цвет которых прозрачен ( transparent ), все значения длин равны 0 , и где inset соответствует более длинному списку.
Формальное определение
Начальное значение | none |
---|---|
Применяется к | все элементы. Это также применяется к ::first-letter . |
Наследуется | нет |
Обработка значения | любая абсолютная длина; работает любой указанный цвет; если другое не указано |
Animation type | список теней |
Формальный синтаксис
box-shadow =
none | (en-US)
# (en-US)
=
? (en-US) && (en-US)
[ (en-US) (en-US) ? (en-US) ? (en-US) ] (en-US) && (en-US)
inset? (en-US)
Примеры
Добавление трёх теней
В этом примере применяется сразу три тени: внутренняя тень, обычная внешняя отбрасываемая тень, а также тень размером 2 пикселя, имитирующая рамку (для создания рамки можно было воспользоваться outline (en-US)).
HTML
blockquote>q>Меня уколют ваши речи,br/> Об ваши взгляды обожгусь,br/> И ранит ложь сильней картечиbr/> Но все равно я поднимусь.q> p>— Майя Энджелоуp> blockquote>
CSS
blockquote padding: 20px; box-shadow: inset 0 -3em 3em rgba(0,0,0,0.1), 0 0 0 2px rgb(255,255,255), 0.3em 0.3em 1em rgba(0,0,0,0.3); >
Результат
Использование нулевых значений для смещений и радиуса размытия
Когда смещение по X ( x-offset ), смещение по Y ( y-offset ) и радиус размытия ( blur ) равны нулю, тень будет представлять собой цветной контур одинакового размера на всех сторонах блока. Тени отображаются с конца списка, поэтому первая тень накладывается поверх последующих. Когда в border-radius указано значение по умолчанию 0 , углы тени становятся прямыми углами. Соответственно, если указать в border-radius любое другое значение, углы станут закруглёнными.
Чтобы тень не перекрывала соседние элементы и не выходила за границу содержащего блока, был добавлен внешний отступ размером, равный самому большому радиусу размытия в списке теней. Тень не влияет на размеры блочной модели.
HTML
Set Box Shadow Only at Bottom in CSS
This article will introduce sets box-shadow only to the bottom of the box in CSS.
Use the box-shadow Property to Set the Bottom Box Shadow in CSS
We can use the box-shadow property to set the shadow only at the bottom of the box. The box-shadow property sets the shadow of the selected element.
The property takes several options. First, let’s understand the property from its syntax, shown below.
box-shadow: [h-offset] [v-offset] [blur-radius] [spread-radius] [color];
It is essential to understand how the box-shadow property works to implement it. The h-offset option sets the shadow in the horizontal direction of the element.
The positive value will set the shadow to the right direction of the element, while the negative value will set the shadow to the left direction of the element.
Likewise, the v-offset option sets the shadow vertically. Again, the positive value sets the shadow to the bottom, while the negative value sets it to the top of the element.
The blur-radius option indicates the blur radius of the shadow. As the blur radius increases, the shadow becomes more blurred.
The spread-radius option sets the size of the shadow to the element. The positive value increases the shadow’s size while the negative value decreases.
We can also use the color option to set the color of the shadow. However, the options blur-radius , spread-radius and color are optional.
Now that we have learned how the box-shadow property works, it’s time to implement it to create a bottom shadow to a box.
For that, we can set h-offset to 0 and give some value to v-offset . As a result, the shadow will appear only at the bottom of the box.
For example, create a box with a certain height and width. Set the background-color property to black .
Next, use the box-shadow property to set the various options. Set 0 for h-offset , 8px for v-offset , 2px for blur-radius , -2px for spread-radius and the color as gray .
As a result, we get a black box with a grey shadow at its bottom. Thus, we learned how to use the box-shadow property to set the shadow to the bottom of the box in CSS.
ocean90 / box-shadow.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Thank you very much! Very neat solution.
Very cool! Thanks for sharing! I created a Codepen for the rules and added a few others as well: http://codepen.io/zeckdude/pen/oxywmm
/* Shadows */ .shadow-top < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75); >.shadow-right < box-shadow: 10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-bottom < box-shadow: 0 10px 20px -5px rgba(115,115,115,0.75); >.shadow-left < box-shadow: -10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-all < box-shadow: 0 0 20px rgba(115,115,115,0.75); >.shadow-top-right < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75), 10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-top-bottom < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75), 0 10px 20px -5px rgba(115,115,115,0.75); >.shadow-top-left < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75), -10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-bottom-right < box-shadow: 0 10px 20px -5px rgba(115,115,115,0.75), 10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-left-right < box-shadow: -10px 0 20px -5px rgba(115,115,115,0.75), 10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-bottom-left < box-shadow: 0 10px 20px -5px rgba(115,115,115,0.75), -10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-top-bottom-right < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75), 0 10px 20px -5px rgba(115,115,115,0.75), 10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-top-bottom-left < box-shadow: 0 -10px 20px -5px rgba(115,115,115,0.75), 0 10px 20px -5px rgba(115,115,115,0.75), -10px 0 20px -5px rgba(115,115,115,0.75); >.shadow-inset
This was always a challenge for me. Thanks
Just what I needed; thank you!!
Thanks it worked for me. Just what I needed 👍
This is good except one issue. If two boxes are stacked and you want to add a left or right shadow, there will be gaps like in below screenshot.
with border removed and with darker shade it look like below
Perfect! Got it working! Thanks @sksar!
thanks so much, very usefull!
Nice ! Thank you for sharing
Here’s a complete list for one-sided, two-sided and three-sided variants: https://codepen.io/eyecatchup/full/wLZgMJ
Thanks, great illustration
Thanks a ton!
What if I want on the top as well as bottom?
How to Set Box Shadow Only at Bottom in CSS?
To add style and design to text and elements, the shadow effect is used. It can be added to an element with the “box-shadow” CSS property. By using commas, you can set multiple effects at once, i.e., horizontal shadow, vertical shadow, blur-radius, etc. This property provides different features of the image using color components.
This manual will provide the method related to setting “box-shadow” only at the bottom of an element.
box-shadow CSS Property
CSS offers a property named “box-shadow” that allows us to set a shadow to any element or image. This property has the following aspects:
-
- offset-x: It is used to add horizontal shadow.
- offset-y: It is used to add vertical shadow.
- color: It is used to set the color of the shadow.
Syntax
To clarify these points, let us move to the syntax of drop-shadow:
-
- offset-x and offset-y will be positive or negative.
- In horizontal, a positive value is used to add the effect on the right side, and a negative is for the left side.
- In vertical, the positive value is for the bottom side, and the negative is for the top.
- blur-radius makes the shadow brighter or lighter.
- In the place of color, you will assign any color you want to give to the image.
For better understanding, let us implement a practical example of the “box-shadow” property.
Example: How to Set Box Shadow Only at Bottom in CSS?
We will apply the box shadow effect to an image. For this first, we will add an image in HTML, and then we will apply the CSS property “box-shadow” to it:
This will give the following output:
Let us move to add a shadow effect on the bottom of the image:
The above values represent the following points:
-
- offset-x is “0px” because we do not want to display shadow horizontally.
- offset-y is “15px” to set the width of the shadow. It must be positive because it displays a shadow at the bottom of the image.
- blur-radius is “5px”. It makes the shadow lighter.
- The color of the shadow is “orange”.
In this image, we can see shadow at the bottom.
Conclusion
To display the shadow at the bottom of the image, the “box-shadow” property is used. For this purpose, offset-x is set as “0”, offset-y is any positive value, and the color you want to display is also set. With the help of an example, this article has explained how to display shadows only at the bottom of the image.
About the author
Anees Asghar
I am a self-motivated IT professional having more than one year of industry experience in technical writing. I am passionate about writing on the topics related to web development.