Css свойство border-style
Содержание:
Использование свойств для одиночных границ
Мы с Вами рассмотрели универсальное свойство border, которое позволяет установить все свойства границ в одном объявлении, но что нам делать, если нам необходимо стилизовать каждую границу элемента по-разному? Для этого в CSS существует четыре универсальных свойства для каждой стороны по отдельности:
- border-top (устанавливает все свойства верхней границы в одном объявлении).
- border-right (устанавливает все свойства правой границы в одном объявлении).
- border-bottom (устанавливает все свойства нижней границы в одном объявлении).
- border-left (устанавливает все свойства левой границы в одном объявлении).
Эти свойства работают аналогично свойству border, разница заключается лишь в том, что используя свойство border-* вы стилизуете выбранную сторону, а не все стороны сразу. Разрешается использовать объявление, в котором одно из значений отсутствует. Если вы опускаете какое-то значение, то значение получает значение по умолчанию. Принцип работы свойства изображен ниже:
Рис. 88. Пример работы универсального свойства border-top.
В данном примере мы задаем сплошную границу шириной 10 пикселей черного цвета для верхней границы.
Как вы уже поняли, эти свойства тоже являются универсальными и отвечают за указание ширины, стиля и цвета для конкретной стороны в одном объявлении. Случаются ситуации, в которых вам необходимы минимальные манипуляции с конкретной границей элемента, для этих целей в CSS существуют свойства, которые позволяют работать со стилем, с цветом и шириной границы необходимой нам стороны по отдельности:
Верхняя граница:
- border-top-width (устанавливает ширину верхней границы).
- border-top-style (устанавливает стиль верхней границы).
- border-top-color (устанавливает цвет верхней границы).
Правая граница:
- border-right-width (устанавливает ширину правой границы).
- border-right-style (устанавливает стиль правой границы).
- border-right-color (устанавливает цвет правой границы).
Нижняя граница:
- border-bottom-width (устанавливает ширину нижней границы).
- border-bottom-style (устанавливает стиль нижней границы).
- border-bottom-color (устанавливает цвет нижней границы).
Левая граница:
- border-left-width (устанавливает ширину левой границы).
- border-left-style (устанавливает стиль левой границы).
- border-left-color (устанавливает цвет левой границы).
Давайте рассмотрим пример, чтобы закрепить полученные знания:
<!DOCTYPE html>
<html>
<head>
<title>Пример использования свойств для одиночных границ</title>
<style>
.primer {
border-left: 4px solid violet; /* устанавливаем сплошную границу размером 4px фиолетового цвета */
border-bottom: .1em solid; /* устанавливаем сплошную границу размером .1em цвета элемента (по умолчанию) */
}
.primer2 {
border: 1px solid green; /* устанавливаем сплошную границу размером 1px зеленого цвета */
border-bottom-style: none; /* устанавливаем стиль границы снизу - отсутствие границы */
border-left-width: 3px; /* устанавливаем ширину границы с левой стороны 3px */
}
</style>
</head>
<body>
<div class = "primer">Абзац с классом primer1</div></br>
<div class = "primer2">Абзац с классом primer2</div>
</body>
</html>
В данном примере для абзаца с классом primer1 мы указали универсальным свойством border-left сплошную границу с левой стороны шириной 4 пикселя фиолетового цвета, а для нижней границы указали, что она будет сплошная шириной 0.1em (по умолчанию черного цвета).
Для абзаца с классом primer2 универсальным свойством border мы указали для всех сторон элемента сплошную границу размером 1 пиксель зеленого цвета, при этом свойством border-bottom-style со значением none мы убрали границу снизу, а свойством border-left-width увеличили размер границы слева до 3 пикселей.
Результат нашего примера:
Рис. 89 Пример использования свойств для одиночных границ.
Оформление рамок HTML-элементов с помощью CSS-свойств
1. Стиль рамки border-style
По умолчанию рамки всегда отрисовываются поверх фона элемента, фон распространяется до внешнего края элемента. Стиль рамки определяет ее отображение, без этого свойства рамки не будут видны вообще. Для элемента можно задавать рамку для всех сторон одновременно с помощью свойства border-style или для каждой стороны отдельно с помощью уточняющих свойств border-top-style и т.д. Не наследуется.
| border-style(border-top-style, border-right-style, border-bottom-style, border-left-style) | |
|---|---|
| Значения: | |
| none | Значение по умолчанию, означает отсутствие рамки. Также убирает рамку элемента из группы элементов с установленным значением данного свойства. |
| hidden | Эквивалентно none. |
| dotted |
dotted |
| dashed |
dashed |
| solid |
solid |
| double |
double |
| groove |
groove |
| ridge |
ridge |
| inset |
inset |
| outset |
outset |
| {1,4} |
Одновременное перечисление четырех разных стилей для рамок элемента, только для свойства border-style:{border-style: solid dotted none dotted;}
|
| initial | Устанавливает значение свойства в значение по умолчанию. |
| inherit | Наследует значение свойства от родительского элемента. |
Синтаксис
2. Цвет рамки border-color
Свойство задаёт цвет рамок всех сторон одновременно. С помощью уточняющих свойств можно установить свой цвет для рамки каждой стороны элемента. Если для рамки цвет не задан, то он будет таким же, как и цвет текста элемента. Если в элементе нет текста, то цвет рамки будет таким же, как и цвет текста родительского элемента. Не наследуется.
| border-color(border-top-color, border-right-color, border-bottom-color, border-left-color) | |
|---|---|
| Значения: | |
| transparent | Устанавливает прозрачный цвет для рамки. При этом ширина рамки остается. Можно использовать для смены цвета рамки при наведении курсора мыши на элемент, чтобы избежать смещение элемента. |
| цвет | Цвет рамок задается при помощи значений свойства .
{border-color: #cacd58;} |
| {1,4} |
Одновременное перечисление четырех разных цветов для рамок элемента, только для свойства border-color:{border-color: #cacd58 #5faf8a #b9cea5 #aab238;}
|
| initial | Устанавливает значение свойства в значение по умолчанию. |
| inherit | Наследует значение свойства от родительского элемента. |
Синтаксис
3. Ширина рамки border-width
Ширина рамки задается с помощью единиц измерения длины или ключевых слов. Если для свойства border-style задано значение none, и для рамки элемента установлена какая-то ширина, то в данном случае ширина рамки приравнивается к нулю. Не наследуется.
| border-width(border-top-width, border-right-width, border-bottom-width, border-left-width) | |
|---|---|
| Значения: | |
| thin / medium / thick | Ключевые слова, устанавливают ширину рамки относительно друг друга. Первое значение уже, чем второе, второе — тоньше третьего. Значение по умолчанию — medium |
| width (px, em) |
{border-width: 5px;} |
| {1,4} |
Возможность одновременного задания четырех разных ширин для рамок элемента, только для свойства border-width:{border-width: 5px 10px 15px 3px;}
|
| initial | Устанавливает значение свойства в значение по умолчанию. |
| inherit | Наследует значение свойства от родительского элемента. |
Синтаксис
4. Задание рамки одним свойством
Свойство border позволяет объединить в себе следующие свойства: border-width, border-style, border-color, например:
При этом заданные свойства будут применяться ко всем границам элемента одновременно. Если какое-то из значений не указано, его место займет значение по умолчанию.
5. Задание рамки для одной границы элемента
В случае, когда необходимо задать разный стиль границ элемента, можно воспользоваться краткой записью для соответствующей границы.
Перечисленные ниже свойства объединяют в одно объявление следующие свойства: border-width, border-style и border-color. Перечень свойств указывается в заданном порядке, при этом одно или два значения могут быть пропущены, в этом случае их значения примут значения по умолчанию.
Стиль верхней границы задается с помощью свойства border-top, нижней — border-bottom, левой — border-left, правой — border-right.
Синтаксис
CSS-фон
CSS content
Hoverable Borders
The w3-hover-border-color classes change the color of the border on mouse-over:
Border that turns red on hover.
Red border that turns green on hover.
Example
<div class=»w3-panel w3-border w3-hover-border-red»>
<p>Border that turns red on hover</p>
</div>
<div class=»w3-panel w3-border w3-border-red w3-hover-border-green»>
<p>Red border that turns green on hover</p>
</div>
Thick (invisible) left border that turns green on hover.
Example
<div class=»w3-panel w3-leftbar w3-border-white w3-hover-border-green»>
<p>Thick (invisible) left border that turns green on hover.</p>
</div><div class=»w3-panel w3-bottombar w3-border-white w3-hover-border-green»>
<p>Thick (invisible) bottom border that turns green on hover.</p>
</div>
Thick white (invisible) border that turns green on hover.
Thick white (invisible) border that turns black on hover.
Example
<div style=»border:16px solid white» class=»w3-panel w3-hover-border-green»>
<p>Thick (invisible) border that turns green on hover.</p></div>
<div style=»border:16px solid white» class=»w3-panel w3-hover-border-black»>
<p>Thick (invisible) border that turns black on hover.</p></div>
❮ Previous
Next ❯
Метод 5
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
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
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
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-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
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
scroll-behavior
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
Property Values
| Value | Description | Play it |
|---|---|---|
| none | Specifies no border. This is default | Play it » |
| hidden | The same as «none», except in border conflict resolution for table elements |
Play it » |
| dotted | Specifies a dotted border | Play it » |
| dashed | Specifies a dashed border | Play it » |
| solid | Specifies a solid border | Play it » |
| double | Specifies a double border | Play it » |
| groove | Specifies a 3D grooved border. The effect depends on the border-color value |
Play it » |
| ridge | Specifies a 3D ridged border. The effect depends on the border-color value |
Play it » |
| inset | Specifies a 3D inset border. The effect depends on the border-color value |
Play it » |
| outset | Specifies a 3D outset border. The effect depends on the border-color value |
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 |
Границы справа слева сверху и снизу отдельно.
Для того, что бы определить стиль, цвет и ширину бордюра для одной из сторон элемента, пользуйтесь свойствами border-bottom, border-left, border-right, border-top и их дочерними «коллегами по цеху» список которых приведён ниже:
border-bottom
- border-bottom-color — Устанавливает цвет нижней границы элемента.
- border-bottom-style — Определяет стиль нижней границы элемента.
- border-bottom-width — Определяет ширину нижней границы элемента.
border-left
- border-left-color — Устанавливает цвет левой границы элемента.
- border-left-style — Определяет стиль левой границы элемента.
- border-left-width — Определяет ширину левой границы элемента.
border-right
- border-right-color — Устанавливает цвет правой границы элемента.
- border-right-style — Определяет стиль правой границы элемента.
- border-right-width — Определяет ширину правой границы элемента.
border-top
- border-top-color — Устанавливает цвет верхней границы элемента.
- border-top-style — Определяет стиль верхней границы элемента.
- border-top-width — Определяет ширину верхней границы элемента.
Не буду описывать каждый из них, думаю и так понятно, что дело обстоит, так же как и с их сородичами, свойствами border-style, border-width и border-color, кроме того факта, что в данном случае свойства указываются для одной из сторон границы элемента.
Приведу пример:
<!DOCTYPE HTML PUBLIC «-//W3C//DTD HTML 4.01 Transitional//EN» «http://www.w3.org/TR/html4/loose.dtd»><html><head><title>Граница слева</title><style type=»text/css»>div{ border-left: 10px solid #008000;background: #c6f2de;}</style></head><body><div><p>В этом примере у контейнера div мы обозначили только его левую границу с помощью свойства border-left написав:</p>div{<br> border-left: 10px solid #008000;<br> background: #c6f2de;<br>}<p>Такого же результата можно было бы добиться прописывая свойства стиля, толщины и цвета для левой границы элемента отдельно.</p><p>Это выглядело бы вот так:</p>div{<br> border-left-color: #008000;<br> border-left-style: solid;<br> border-left-width: 10px;<br> background: #c6f2de;<br>}<p>Кстати Вам этот блок ничего не напоминает? :)</p></div></body></html>
смотреть пример
CSS Учебник
CSS СТАРТCSS ВведениеCSS СинтаксисCSS СелекторыCSS Как подключитьCSS ЦветаCSS background-colorCSS borderCSS marginCSS paddingCSS height/widthCSS Блочная модельCSS КонтурCSS ТекстCSS ШрифтыCSS ИконкиCSS СсылкиCSS СпискиCSS ТаблицыCSS displayCSS max-widthCSS positionCSS overflowCSS float/clearCSS inline-blockCSS ВыравниваниеCSS КомбинаторыCSS Псевдо-классыCSS Псевдо-элементыCSS opacity/transparencyCSS Панель навигацииCSS Выпадающие спискиCSS Галерея изображенийCSS Спрайты изображенийCSS Селекторы атрибутовCSS ФормыCSS СчётчикиCSS Макет веб-сайтаCSS ЕдиницыCSS Специфичности
CSS Border Style
The property specifies what kind of border to display.
The following values are allowed:
- — Defines a dotted border
- — Defines a dashed border
- — Defines a solid border
- — Defines a double border
- — Defines a 3D grooved border. The effect depends on the border-color value
- — Defines a 3D ridged border. The effect depends on the border-color value
- — Defines a 3D inset border. The effect depends on the border-color value
- — Defines a 3D outset border. The effect depends on the border-color value
- — Defines no border
- — Defines a hidden border
The property can have from one to four values (for
the top border, right border, bottom border, and the left border).
Example
Demonstration of the different border styles:
p.dotted {border-style: dotted;}p.dashed
{border-style: dashed;}p.solid {border-style: solid;}p.double
{border-style: double;}p.groove {border-style: groove;}p.ridge
{border-style: ridge;}p.inset {border-style: inset;}p.outset
{border-style: outset;}p.none {border-style: none;}p.hidden {border-style: hidden;}
p.mix {border-style: dotted dashed solid double;}
Result:
A dotted border.
A dashed border.
A solid border.
A double border.
A groove border. The effect depends on the border-color value.
A ridge border. The effect depends on the border-color value.
An inset border. The effect depends on the border-color value.
An outset border. The effect depends on the border-color value.
No border.
A hidden border.
A mixed border.
Note: None of the OTHER CSS border properties (which you will learn more about in the next chapters) will have ANY effect unless the
property is set!
❮ Previous
Next ❯
CSS Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Style
Font Size
Font Google
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
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
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
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-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
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
scroll-behavior
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 border-image — Different Slice Values
Different slice values completely changes the look of the border:
Example 1:
border-image: url(border.png) 50 round;
Example 2:
border-image: url(border.png) 20% round;
Example 3:
border-image: url(border.png) 30% round;
Here is the code:
Example
#borderimg1 { border: 10px solid transparent;
padding: 15px; border-image: url(border.png)
50 round;}#borderimg2 {
border: 10px solid transparent; padding: 15px;
border-image: url(border.png) 20% round;}
#borderimg3 { border: 10px solid transparent;
padding: 15px; border-image: url(border.png)
30% round;}
CSS Border Image Properties
| Property | Description |
|---|---|
| border-image | A shorthand property for setting all the border-image-* properties |
| border-image-source | Specifies the path to the image to be used as a border |
| border-image-slice | Specifies how to slice the border image |
| border-image-width | Specifies the widths of the border image |
| border-image-outset | Specifies the amount by which the border image area extends beyond the border box |
| border-image-repeat | Specifies whether the border image should be repeated, rounded or stretched |
❮ Previous
Next ❯
W3.CSS Border Classes
W3.CSS provides the following border classes:
| Class | Defines |
|---|---|
| w3-border | Adds borders (top, right, bottom, left) to an element |
| w3-border-top | Adds a top border to an element |
| w3-border-right | Adds a right border to an element |
| w3-border-bottom | Adds a bottom border to an element |
| w3-border-left | Adds a left border to an element |
| w3-border-0 | Removes all borders |
| w3-border-color | Displays the border in a specified color (like red, blue, etc) |
| w3-hover-border-color | Adds a hoverable border color |
| w3-bottombar | Adds a thick bottom border to an element |
| w3-leftbar | Adds a thick left border to an element |
| w3-rightbar | Adds a thick right border to an element |
| w3-topbar | Adds a thick top border to an element |
Пример использования
<!DOCTYPE html>
<html>
<head>
<title>Использование изображения в качестве границы</title>
<style>
div {
width : 150px; /* устанавливаем ширину блока */
height : 50px; /* устанавливаем высоту блока */
padding : 50px; /* устанавливаем величину внутреннего отступа элемента */
border : 55px solid transparent; /* прозрачная сплошная граница размером 55px */
border-image : url(ramka.png) 100 round; /* указываем путь к изображению, устанавливаем смещение 100px от верхней, правой, нижней и левой кромки изображения, указываем, что изображение масштабируемо и должно повторяться, пока не заполнит зазор между двумя границами. */
}
</style>
</head>
<body>
<div class = "test">Ваш текст</div>
</body>
</html>
В этом примере мы используем изображение 800 на 687, которое мы установили в качестве изображения рамки. Кроме того, установили смещение 100px от верхней, правой, нижней и левой кромки изображения и указали, что изображение масштабируемо и должно повторяться, пока не заполнит зазор между двумя границами.
Результат нашего примера:

Пример использования изображения в качестве границы.
Рассмотрим следующий пример в котором мы установим в качестве границы-изображения линейный градиент, повторяющийся линейный градиент и радиальный градиент:
<!DOCTYPE html>
<html>
<head>
<title>Изображение-граница на CSS</title>
<style>
div {
display : inline-block; /* устанавливаем элементы <div> как блочно-строчные (выстраиваем в линейку) */
width : 150px; /* устанавливаем ширину блока */
height : 70px; /* устанавливаем высоту блока */
border : 10px solid transparent; /* прозрачная сплошная граница размером 10px для все элементов <div> */
margin-right : 20px; /* устанавливаем отступ справа 20px */
}
.test {
border-image : repeating-linear-gradient( 45deg, red, red 1%, yellow 1%, red 8%) 10; /* устанавливаем повторяющийся линейный градиент, который будет использован в качестве границы-изображения */
}
.test2 {
border-image : linear-gradient(to right, pink , green) 10;; /* устанавливаем линейный градиент, который будет использован в качестве границы-изображения */
}
.test3 {
border-image : radial-gradient(yellow 50%, green 65%, red 100%) 10; /* устанавливаем круговой градиент, который будет использован в качестве границы-изображения */
}
.test4 {
border-image : url(img-border.png) 25 stretch; /* указываем путь к изображению, устанавливаем смещение 25px от верхней, правой, нижней и левой кромки изображения, указываем, что изображение будет растянуто на всю длину. */
}
.test5 {
border-image : url(img-border.png) 15 round; /* указываем путь к изображению, устанавливаем смещение 15px от верхней, правой, нижней и левой кромки изображения, указываем, что изображение масштабируемо и должно повторяться, пока не заполнит зазор между двумя границами. */
}
</style>
</head>
<body>
<p><b>Использование градиентов:</b></p>
<div class = "test"></div>
<div class = "test2"></div>
<div class = "test3"></div>
<p><b>Использование изображения:</b></p>
<img src = "img-border.png" alt = "ramka">
<div class = "test4"></div>
<div class = "test5"></div>
</body>
</html>
В этом примере с использованием свойства border-image мы установили различные значения для изображения, либо градиентов которые использованы вместо границы вокруг наших элементов.
Результат нашего примера:

Пример использования свойства border-image.CSS свойства
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
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
break-after
break-before
break-inside
caption-side
caret-color
@charset
clear
clip
clip-path
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-feature-settings
font-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
font-variant-caps
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
scroll-behavior
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 Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Style
Font Size
Font Google
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS Specificity
