Borders in the CSS Box Model (Live Playground)
Borders are an important component of the CSS box model, providing a visible line that surrounds the content and padding of an element. In this tutorial, you will learn about borders, how to set individual and shorthand border properties, and how they affect the layout of elements, along with sample code and simple explanations.
Individual border properties
You can set border properties individually for each side of an element:
- border-top
- border-right
- border-bottom
- border-left
Each side property can be further broken down into three sub-properties:
- Style:
border-top-style
,border-right-style
,border-bottom-style
,border-left-style
- Width:
border-top-width
,border-right-width
,border-bottom-width
,border-left-width
- Color:
border-top-color
,border-right-color
,border-bottom-color
,border-left-color
Example:
div {
background-color: lightblue;
border-top: 5px solid darkblue;
border-bottom: 3px dashed darkblue;
}
<div>This div element has individual border properties for the top and bottom sides.</div>
In this example, the div
element has a 5px solid darkblue border on the top and a 3px dashed darkblue border on the bottom.
Shorthand border property
The shorthand border
property allows you to set border properties for all four sides in a single line of code:
border: width style color;
Example:
div {
background-color: lightblue;
border: 2px solid darkblue;
}
<div>This div element has a shorthand border property for all sides.</div>
In this example, the div
element has a 2px solid darkblue border on all sides using the shorthand border property.
The effect of borders on layout
Borders affect the total size of an element and can influence the positioning of surrounding elements. They do not, however, affect the size of the content area or padding.
Example:
.container {
display: flex;
}
.box {
width: 100px;
height: 100px;
background-color: lightblue;
margin-right: 10px;
}
.box-border {
border: 5px solid darkblue;
}
<div class="container">
<div class="box">No border</div>
<div class="box box-border">With border</div>
</div>
In this example, the div
element with a border has a larger total size but retains the same content size and padding as the div element without a border.
Conclusion
In this tutorial, you learned about borders in the CSS box model and how to set individual and shorthand border properties. By understanding the role of borders in the box model and how they affect the layout of elements, you can create more visually appealing and consistent designs across your web pages.