Basics
CSS – Cascading Style Sheets are used for styling HTML elements. Styles are applied using a locator and a style definition:
/* Locator */
div {
/* style key-pair definition */
color: blue;
}
The locator locates HTML elements; in this example, the locator finds all divs in the document. The style is then applied to all elements that match the locator.
<body>
<div>
A div
</div>
<span>
A span
</span>
</body>
Output:
Selectors
- Simple selectors
- Combinator selectors
- Pseudo-class selectors
- Pseudo-elements selectors
- Attribute selectors
Simple selectors
Simple selectors are; element, id, class and group selectors.
Example HTML
<body>
<div id="div-id">A div</div>
<span id="id2">A span</span>
</body>
The element selector is the most basic of the selectors and is used when selecting an HTML element, like a div or span. The example will select all divs, and make them red and all the spans blue.
div {
color: red;
}
span {
color: blue;
}
The id selector selects based on an element id and selects all elements with the specified id.
#div-id {
background-color: blueviolet;
}
#span-id {
background-color: yellow;
}
The class selector selects elements with the specified class attribute.
.red-border {
border-color: red;
border-style: solid;
border-width: 2px;
}
As shown in this example, multiple style declarations can be applied to achieve the desired look. This style adds a red solid 2px wide border.
Selectors can be grouped to remove duplication.
h1, div, p {
color: green;
}
Here all h1, div and p elements are selected and the color is set to green.
More to come, stay tuned…