How to add border in CSS
To add a border to an HTML element using CSS, you can use the border
property. The border
property allows you to define the width, style, and color of the border around the element.
Here’s an example of how to add a border to an element:
HTML:
<div class="border-example">
This is a div element with a border.
</div>
CSS:
.border-example {
border: 2px solid #007bff; /* Replace with your desired border width and color */
padding: 10px; /* Optional: Add padding to create some space between the text and the border */
}
In this example, we have a <div>
element with the class “border-example.” We target this element in CSS using the class selector .border-example
and use the border
property to create a border around the element.
The border
property value consists of three parts:
- Border Width: The first part specifies the width of the border. You can use values like
1px
,2px
,3px
, etc., to set the border width in pixels. - Border Style: The second part defines the style of the border, such as
solid
,dotted
,dashed
,double
,groove
,ridge
,inset
,outset
, etc. - Border Color: The third part sets the color of the border. You can use color names, hexadecimal values, RGB values, or HSL values to define the color.
You can also specify different border widths for individual sides using the border-width
, border-style
, and border-color
properties separately. For example:
.border-example {
border-width: 2px 4px; /* 2px top and bottom, 4px left and right */
border-style: solid;
border-color: #007bff;
}
Additionally, you can apply rounded corners to the border using the border-radius
property:
.border-example {
border: 2px solid #007bff;
border-radius: 10px; /* Apply rounded corners */
}
By using the border
property along with other CSS properties, you can create various border styles and designs for different elements on your webpage.