How to Add Border on Only One Side in Shorter Way in CSS?
Last Updated :
18 Oct, 2024
Borders are useful for defining and separating elements on your webpage, giving it a more organized look. You can easily add a border to just one side of an element using CSS. By using specific border properties, you can customize which side gets the border, helping to create a cleaner design.
Approach to Add Border on Only One Side
To add a border to just one side of an element in CSS, first, choose the HTML element you want to style, like a <div> or <p>. Then, use the specific property for the side you want to change; for example, if you want a border on the left, use border-left. You can set the borderâs width, style (solid or dashed), and color. If you don’t want any borders on the other side, set them to none. For instance, you might write border-top: none; to remove the top border.
Syntax:
// With traditional CSS: CSS ruleset
border-{any side}: values;
Example: The code demonstrates how we can add a border to only one side using CSS and the border-{any side} property.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Is there a shorter way to write a border
on only one side
</title>
<style>
.container {
display: flex;
}
.container-1 {
border-left: 0.25rem solid green;
background-color: gainsboro;
width: 250px;
height: 100px;
margin: 5% 6% 0 10%;
}
.container-2 {
border-bottom: 0.25rem solid green;
background: gainsboro;
margin-top: 5%;
width: 250px;
height: 100px;
}
.container-3 {
border-right: 0.25rem solid green;
background-color: gainsboro;
width: 250px;
height: 100px;
margin: 5% 6% 0 10%;
}
.container-4 {
border-top: 0.25rem solid green;
background: gainsboro;
width: 250px;
height: 100px;
margin-top: 5%;
}
p {
margin-left: 18%;
}
</style>
</head>
<body>
<h1 style="color: green; margin: 1rem">
</h1>
<h3 style="margin: 1rem; margin-top: -1rem">
Is there a shorter way to write a border
on only one side?
</h3>
<div class="container">
<div class="container-1"></div>
<div class="container-2"></div>
</div>
<div class="container">
<p>with <code>only left border</code></p>
<p>with <code>only bottom border</code></p>
</div>
<div class="container">
<div class="container-3"></div>
<div class="container-4"></div>
</div>
<div class="container">
<p>with <code>only right border</code></p>
<p>with <code>only top border</code></p>
</div>
</body>
</html>
Output:

Output