Adding Borders Using CSS
Borders provide visual separation between elements on a page. You can add borders around anything in HTML. Borders are added with the border CSS property.
1. Border
When creating a border with CSS, you can set three properties:
- Border width (border-width): The width or thickness of the border.
- Border style (border-style): CSS supports a number of border styles.
- Border color (border-color): The color used to display the border.
These three items are set in a list, separated by a space. For example,
border: 2px solid black;
In this example, a border would be created with 2 pixel thickness. The border would be solid and would be black in color.
Border Styles
You can choose any of these styles:
- Solid: A single solid line around the element.
- Double: Two lines around the element with a gap between them. The border width is the combined width of both lines and the gap.
- Groove: Uses shading to simulate a groove etched in the page.
- Ridge: Uses shading to simulate a ridge drawn on the page.
- Inset: Uses shading to simulate a pressed-in button.
- Outset: Uses shading to simulate a button sticking out from the page.
- Dashed: A dashed line around the element.
- Dotted: A dotted line around the element.
2. Rounded Corners
The border-radius property creates rounded corners without the need for images or additional markup. For example,
border-radius: 1em;
The border-radius property can be applied to all elements, except the table element when the border-collapse property is set to collapse.
It adds a consistent border to each corner. You can also define the border radius for each corner by providing four values: top left, top right, bottom right and bottom left.
3. Padding
When you put a border, you often add breathing room ot padding between the border and content. The padding property changes how close the text will come to the inside edge of the border. Padding can be applied to any element, regardless of whether it has borders, in order to move that element's contents.
For example,
.boxed {
border: 5px solid red;
padding: .5em;
}
you can also add padding so that the contents move away from the top, bottom, right, or left, or in any combination. This is accomplished with the padding-top, padding-bottom, padding-right, and padding-left properties, respectively.
4. Margin
You can put margins around paragraphs, headings, and many other HTML elements. A margin creates extra space around the top, bottom, or sides of an element. For example,
.offset {
margin: 2em 2em 2em 2em;
}
Here, the amount of white space is two times the size of default text. A more concise way to code equal margins on all four sides is
.offset {
margin: 2em;
}
When you specify all four margins in one statement, you specify them in clockwise order, starting at the top. Instead of specifying all four margins, you can specify individual margins. For example,
margin-bottom: 1em;
You can also specify margin-top, margin-right, and margin-left.