CSS selectors are used to target specific elements in your HTML document. They allow you to apply styles to elements based on their tags, classes, IDs, attributes, and more.
Common Selectors
- Element selectors: Target elements based on their tag name (e.g., p, h1, div).
- Class selectors: Target elements with a specific class attribute (e.g., .container, .item).
- ID selectors: Target elements with a unique ID attribute (e.g., #header).
- Attribute selectors: Target elements based on their attributes (e.g., [href], [data-foo=”bar”]).
Example:
CSS
p {
color: blue;
}
.container {
background-color: #f0f0f0;
}
#header {
font-size: 24px;
}
Units
CSS uses various units to measure lengths, sizes, and distances. Some common units include:
- Pixels (px): Absolute units that represent the physical pixels on a screen.
- Relative units:
- em: Relative to the font size of the element’s parent.
- rem: Relative to the root element’s font size.
- %: Relative to the size of the containing element.
- vw: Relative to the viewport width.
- vh: Relative to the viewport height.
Example:
CSS
body {
font-size: 16px;
}
.element {
width: 50%;
padding: 1rem;
}
CSS Capabilities
CSS offers a wide range of capabilities for styling and formatting web content. Some key areas include:
- Typography: Control font families, sizes, weights, styles, and line heights.
- Colors: Set colors for text, backgrounds, borders, and other elements.
- Layouts: Create responsive layouts using techniques like Flexbox and CSS Grid.
- Box Model: Understand the box model, which consists of the content area, padding, border, and margin.
- Pseudo-classes: Target elements based on their state (e.g., :hover, :active).
- Pseudo-elements: Create generated content within elements (e.g., ::before, ::after).
By effectively using CSS selectors, units, and capabilities, you can create visually appealing and responsive web designs.