Все о свойстве border
Все знакомы с css параметром border, но есть ли вещи, которые мы не знаем о нем?
Основы
border-width: thick; border-style: solid; border-color: black;
Например у параметра border-width есть три параметра: thin, medium, thick:
Если необходимо менять цвет границы при наведении на объект:
Border-Radius
border-radius — это новый параметр CSS3 для отображения закругленных углов, который корректно работает во всех современных браузерах, за исключением Internet Explorer 8 (и более старых версий).
Для каждого угла можно назначить свое закругление:
border-top-left-radius: 20px; border-top-right-radius: 0; border-bottom-right-radius: 30px; border-bottom-left-radius: 0;
В приведенном примере необязательно назначать «0» border-top-right-radius и border-bottom-left-radius, если они не наследуют значения, которые должны быть изменены.
Всю конструкцию можно сжать в одну строку:
/* top left, top right, bottom right, bottom left */ border-radius: 20px 0 30px 0;
Здесь описаны самые простые и популярные примеры применения параметра border. Перейдем к более сложным.
Несколько границ
Border-Style
solid, dashed, and dotted — самые популярные значения параметра border-style, но давайте рассмотрим другие, например, groove and ridge.
border: 20px groove #e3e3e3;
border-color: #e3e3e3; border-width: 20px; border-style: groove;
Outline
Этот способ отлично работает, но ограничен созданием двойной рамки. Если вам необходимо отобразить несколько границ элемента, то необходимо использовать другую технику.
Псевдоэлементы
.box < width: 200px; height: 200px; background: #e3e3e3; position: relative; border: 10px solid green; >/* Create two boxes with the same width of the container */ .box:after, .box:before < content: ''; position: absolute; top: 0; left: 0; bottom: 0; right: 0; >.box:after < border: 5px solid red; outline: 5px solid yellow; >.box:before
Возможно это не самое элегантное решение, однако оно работает
Box-Shadow
Изменение углов
border-radius: 50px / 100px; /* horizontal radius, vertical radius */
border-top-left-radius: 50px 100px; border-top-right-radius: 50px 100px; border-bottom-right-radius: 50px 100px; border-bottom-left-radius: 50px 100px;
Эта техничка бывает полезна, если необходимо имитировать искривление, а не закругление. Например, так можно получить эффект скрученной бумаги:
CSS фигуры
Наиболее частым примером использования CSS фигур является отображение стрелок. Чтобы понять, как это работает, необходимо разобраться с использованием отдельного border-color для каждой стороны и установкой значения «0» для width и height:
А теперь оставляем только синий треугольник:
Создание Speech Bubble
Теперь нужно расположить стрелку-треугольник в нужном месте. Вот наш цветной квадратик:
Оставляем только четверть квадратика:
Теперь перемещаем ниже и закрашиваем:
.speech-bubble < /* … other styles */ border-radius: 10px; >.speech-bubble:after < content: ''; position: absolute; width: 0; height: 0; border: 15px solid; border-top-color: #292929; top: 100%; left: 50%; margin-left: -15px; /* adjust for border width */ >
Примеры применения:
/* Speech Bubbles Usage: Apply a class of .speech-bubble and .speech-bubble-DIRECTIONHi there*/ .speech-bubble < position: relative; background-color: #292929; width: 200px; height: 150px; line-height: 150px; /* vertically center */ color: white; text-align: center; border-radius: 10px; font-family: sans-serif; >.speech-bubble:after < content: ''; position: absolute; width: 0; height: 0; border: 15px solid; >/* Position the Arrow */ .speech-bubble-top:after < border-bottom-color: #292929; left: 50%; bottom: 100%; margin-left: -15px; >.speech-bubble-right:after < border-left-color: #292929; left: 100%; top: 50%; margin-top: -15px; >.speech-bubble-bottom:after < border-top-color: #292929; top: 100%; left: 50%; margin-left: -15px; >.speech-bubble-left:after
Вертикальное центрирование текста
минус использования line-height при вертикальном центрировании в ограничении текста одной строкой. Для решения этой проблемы, можно применить display: table к нашему Speech Bubble и display: table-cell к тексту:
.speech-bubble < /* other styles */ display: table; >.speech-bubble p
Еще один пример нестандартного использования границ:
Итог
Использование параметра border не ограничивается одним лишь «1px solid black», с помощью границ можно создавать различные фигуры, причем достаточно один раз написать CSS-класс и применять его к множеству элементов на странице.
CSS backgrounds and borders
The CSS backgrounds and borders module provides properties for adding borders, rounded corners, and box shadows to elements.
You can add different types of border styles, including borders made of images of any image type, from raster images to CSS gradients. Borders can be square or rounded, and a different radius can be set for each corner. Elements can be rounded whether or not they have a visible border.
Box shadows include inset and outset shadow, single or multiple shadows, and solid or allowed to fade to transparent. An outer box-shadow casts a shadow as if the border-box of the element were opaque. An inner box-shadow casts a shadow as if everything outside the padding edge were opaque. The shadow can be solid or include a spread distance with the shadow color transitioning to transparent.
The properties in this module also let you define whether cells inside a should have shared or separate borders.
Backgrounds, borders, and box shadows in action
This sample of borders, backgrounds, and box shadows consists of centered background images made of linear and radial gradients. A series of box shadows make the border appear to «pop». The element on the left has a border image set. The element on the right has a rounded dotted border.
The background images are defined with background-image . The images are centered with background-position . Different values of the background-clip property for the multiple background images are used to make the background images stay within the content box. The background color gets clipped to the padding box preventing the background from appearing through the transparent sections for the border-image and the dotted border . The rounded corners in the element on the right are created using the border-radius property. A single box-shadow declaration is used to set all the shadows, both inset and outset.
To see the code for this sample, view the source on GitHub.
Reference
Properties
- background-attachment
- background-clip
- background-color
- background-image
- background-origin
- background-position
- background-repeat
- background-size
- background shorthand
- background-position-x Experimental
- background-position-y Experimental
- background-position-inline Experimental
- background-position-block Experimental
- border-bottom-color
- border-bottom-style
- border-bottom-width
- border-bottom shorthand
- border-left-color
- border-left-style
- border-left-width
- border-left shorthand
- border-right-color
- border-right-style
- border-right-width
- border-right shorthand
- border-top-color
- border-top-style
- border-top-width
- border-top shorthand
- border-color shorthand
- border-style shorthand
- border-width shorthand
- border shorthand
- border-collapse
- border-bottom-left-radius
- border-bottom-right-radius
- border-top-left-radius
- border-top-right-radius
- border-radius shorthand
- border-image-outset
- border-image-repeat
- border-image-slice
- border-image-source
- border-image-width
- border-image shorthand
- box-shadow
Data types
Guides
Explains how to implement decorative images using CSS background images.
Explains how to set one or more backgrounds on an element.
Describes how to change the size and repeating behavior of background images.
Explains how borders, along with other box model properties, impact the CSS box model.
Explains how to create CSS gradient background images.
Related concepts
- border-block-end-color property
- border-block-start-color property
- border-inline-end-color property
- border-inline-start-color property
- border-block-end-style property
- border-block-start-style property
- border-inline-end-style property
- border-inline-start-style property
- border-block-end-width property
- border-block-start-width property
- border-inline-end-width property
- border-inline-start-width property
- border-start-start-radius property
- border-start-end-radius property
- border-end-start-radius property
- border-end-end-radius property
- box-sizing property
- box-decoration-break property
- text-shadow property
- url() CSS function
- data type
- data type
- data type
- currentcolor keyword
Specifications
See also
- Interactive tools that let you visually create borders images, rounded corners, and box shadows:
- Border-image generator
- Border-radius generator
- Box-shadow generator
Found a content problem with this page?
This page was last modified on Jul 17, 2023 by MDN contributors.
Your blueprint for a better internet.