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:

selector {
    property: value;
}

Examples of CSS Selectors

Selectors are fundamental to using CSS effectively. Here are examples of basic selectors:


/* 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 */
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:

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.