CSS Borders
Frame elements with border width, style, color, and radius.
CSS Borders
CSS borders create a visible line around an HTML element. They can help separate content, highlight buttons, design cards, and improve the structure of a webpage.
A border needs three main values:
- Width
- Style
- Colour
.card {
border: 2px solid blue;
}This creates a 2px solid blue border around the card.
Border Width
The border-width property controls the thickness of a border.
.box {
border-width: 3px;
border-style: solid;
}Common values include:
thinmediumthick- A specific size, such as
2px
You can also set a different width for each side:
.box {
border-top-width: 2px;
border-right-width: 4px;
border-bottom-width: 6px;
border-left-width: 8px;
}Border Style
The border-style property controls the appearance of the border.
.notice {
border-style: dashed;
}Common border styles include:
solid– a continuous linedashed– a line made of dashesdotted– a line made of dotsdouble– two solid linesgroove– a carved appearanceridge– a raised appearanceinset– makes the element look pressed inoutset– makes the element look raisednone– removes the border
A border will not appear unless a border style is provided.
Border Colour
The border-color property changes the border's colour.
.warning {
border-style: solid;
border-color: red;
}You can use colour names, HEX, RGB, RGBA, HSL, or HSLA values:
.info {
border-color: #1f4ed8;
}Border Shorthand
The border shorthand combines width, style, and colour in one declaration:
button {
border: 2px solid green;
}The usual order is:
border: width style color;Shorthand keeps the code short and readable.
Styling Individual Sides
Each side can have a different border:
.heading {
border-bottom: 3px solid orange;
}Available properties include:
border-topborder-rightborder-bottomborder-left
This is useful for headings, navigation links, and table rows.
Rounded Borders
The border-radius property creates rounded corners:
.card {
border: 1px solid gray;
border-radius: 12px;
}You can create a circle by using 50%:
.profile-image {
width: 100px;
height: 100px;
border-radius: 50%;
}The element needs equal width and height to form a perfect circle.
Using Borders with CSS Selectors
Selectors decide which elements receive border styles:
/* Universal selector */
* {
box-sizing: border-box;
}
/* Element selector */
input {
border: 1px solid gray;
}
/* Class selector */
.card {
border: 2px solid blue;
}
/* ID selector */
#main-banner {
border-bottom: 4px solid navy;
}
/* Attribute selector */
input[type="email"] {
border-color: green;
}
/* Pseudo-class selector */
button:hover {
border-color: orange;
}
/* Pseudo-element selector */
.title::after {
content: "";
display: block;
border-bottom: 3px solid blue;
}Border and Element Size
Borders can increase an element's total size. Use box-sizing: border-box to include the border within the declared width and height:
* {
box-sizing: border-box;
}This makes element sizes easier to calculate.