CSS Syntax and Usage
Cascading Style Sheets (CSS) is a powerful tool used to style and layout HTML web pages. CSS syntax consists of a set of rules that define how styles are applied to elements within a web page.
What is CSS Syntax?
CSS syntax involves selectors and declarations that determine how styles are applied:
- Selectors identify which HTML elements the CSS rules affect.
- Declarations, placed inside curly braces, specify the properties to be applied to the elements.
selector {
property: value;
}
Examples of CSS Selectors
Selectors are fundamental to using CSS effectively. Here are examples of basic selectors:
- Type selector: targets elements by their tag name.
- Class selector: targets elements by their class attribute.
- ID selector: targets an element by its ID attribute.
- Attribute selector: targets an element by attribute and his value
/* Type selector */
h1 {
color: red;
}
/* Class selector */
.menu {
font-size: 16px;
}
/* ID selector */
#header {
background-color: lightblue;
}
/* Attribute selector */
[target="_blank"]{
color: green;
}
Combining Selectors
Combining selectors allows for more specific targeting of HTML elements:
- Descendant selector: targets elements that are descendants of another element.
- Child selector: targets elements that are direct children of another element.
- Adjacent sibling selector: targets an element directly following another element.
/* Descendant selector */
div .menu {
border: 1px solid black;
}
/* Child selector */
div > .menu {
border: 2px solid red;
}
/* Adjacent sibling selector */
h1 + p {
color: green;
}
These selectors increase the precision with which developers can apply styles, making the CSS more efficient and the site more visually consistent.
Applying CSS to HTML
CSS can be applied inline, internally, or externally:
- Inline: directly within HTML elements using the
styleattribute.<p style="color:red">Text</p> - Internal: within a
<style>element in the HTML document.<style> p{ color:red; } </style> - External: by linking an external CSS file using the
<link>element.<link rel="stylesheet" href="styles.css">
Conclusion
Understanding CSS syntax and selectors is crucial for effectively styling HTML documents. By using a combination of selectors, developers can target elements with precision, ensuring that each element on a webpage looks exactly as intended.