CSS (Cascading Style Sheets) is a stylesheet language used for describing the look and formatting of a document written in HTML or XML. Here is a guide to the basic syntax of CSS with code examples:
Selectors
Selectors are used to target specific HTML elements in order to apply styles to them. They can be based on element type, class, ID, attributes, and more.
Here are some examples of different types of selectors:
- Element selector: targets all instances of a specific HTML element, such as
<h1>
,<p>
, or<ul>
. Example:
cssh1 {
color: red;
}
- Class selector: targets all instances of a specific class attribute. Classes are denoted by a dot (
.
) followed by the class name. Example:
css.highlight {
background-color: yellow;
}
- ID selector: targets a specific HTML element based on its ID attribute. IDs are denoted by a hash (
#
) followed by the ID name. Example:
css#header {
font-size: 24px;
}
- Attribute selector: targets elements with a specific attribute. Example:
cssa[href="https://www.example.com"] {
color: blue;
}
Properties and Values
Once you have selected the HTML element(s) you want to style, you can apply CSS properties and values to them. Properties are the specific attributes you want to set, such as color, font-size, or background-color. Values are the settings you want to apply to those properties.
Here are some examples of common CSS properties and values:
color
: sets the color of text. Example:
cssh1 {
color: red;
}
font-size
: sets the size of the font. Example:
cssp {
font-size: 16px;
}
background-color
: sets the background color of an element. Example:
cssbody {
background-color: white;
}
border
: sets the style, width, and color of an element's border. Example:
cssdiv {
border: 1px solid black;
}
margin
: sets the margin around an element. Example:
cssimg {
margin: 10px;
}
padding
: sets the padding inside an element's border. Example:
cssbutton {
padding: 5px 10px;
}
Comments
You can add comments to your CSS code to help explain what you are doing or to temporarily disable certain styles. Comments are denoted by /*
at the beginning and */
at the end.
Here is an example of a comment:
css/* This is a comment */
In conclusion, CSS is a powerful tool for styling HTML documents. By understanding the basic syntax of CSS, you can create visually appealing and engaging web pages with ease.