In CSS, Rule Sets are the fundamental building blocks that define how HTML elements are styled. Each rule set consists of a selector, which targets the HTML element(s) to be styled, and a declaration block, which contains one or more declarations specifying the styles to be applied.
Example 1: Basic Paragraph Styling
p { /* Selects all <p> (paragraph) elements */
color: blue; /* Sets the text color to blue */
font-size: 16px; /* Sets the font size to 16 pixels */
}
Explanation This example demonstrates a basic rule set targeting all <p>
elements. It sets their text color to blue and their font size to 16 pixels, showcasing how to apply consistent styles across similar elements.
Example 2: Styling a Specific ID
#header { /* Selects the element with the ID "header" */
background-color: lightgray; /* Sets the background color to light gray */
padding: 20px; /* Adds 20 pixels of padding around the content */
}
Explanation Here, a rule set targets a unique HTML element using its ID. This allows for specific styling of a single element, providing precise control over its appearance.
Example 3: Styling Elements by Class
.card { /* Selects all elements with the class "card" */
border: 1px solid #ccc; /* Adds a 1-pixel solid border with a light gray color */
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1); /* Adds a subtle shadow effect */
}
Explanation This example uses a class selector to apply styles to multiple HTML elements that share the same class. This is ideal for reusable styles across various components on a webpage.
Example 4: Grouping Selectors
h1, h2, h3 { /* Selects all <h1>, <h2>, and <h3> elements */
font-family: Arial, sans-serif; /* Sets the font family to Arial or a generic sans-serif */
text-align: center; /* Centers the text horizontally */
}
Explanation In this rule set, multiple selectors are grouped to apply the same styles to different HTML elements simultaneously. This reduces code redundancy and improves maintainability.
Example 5: Descendant Selector
ul li { /* Selects all <li> (list item) elements that are descendants of a <ul> (unordered list) */
list-style-type: square; /* Changes the list item marker to a square */
margin-bottom: 5px; /* Adds a bottom margin of 5 pixels to each list item */
}
Explanation This example uses a descendant selector to target <li>
elements specifically within <ul>
elements. This provides more granular control, allowing for precise styling of nested elements in your web layout.