Specificity, Shared CSS, & Centering Content
Master CSS fundamentals for professional web development
Core CSS Concepts You'll Master
CSS Specificity
Learn how browsers prioritize CSS rules and override styles effectively. Understanding specificity prevents common styling conflicts.
External Stylesheets
Move from embedded to external CSS for better organization and reusability across multiple pages.
Content Centering
Master text-align property and margin auto techniques for professional page layouts.
Below the nav a:visited rule, add this hover rule with matching specificity:
nav a:hover {
color: #e45c09;
}To complete our professional navigation styling, remove the underline on hover by adding the text-decoration property:
nav a:hover {
color: #e45c09;
text-decoration: none;
}For comprehensive accessibility, apply the same styling to the focus state (used by keyboard navigation). Add nav a:focus to the selector—note the critical comma:
nav a:hover, nav a:focus {
color: #e45c09;
text-decoration: none;
}Test both interaction methods: hover with your mouse and tab through the navigation with your keyboard. Both should display the same clean orange styling without underlines.
This attention to accessibility details—ensuring keyboard and mouse users have equivalent experiences—distinguishes professional web development from amateur efforts.
Moving to External CSS
Cut embedded styles
Select and cut all CSS rules from between style tags in HTML file
Paste into main.css
Create or open external CSS file and paste the cut styles
Link stylesheet
Replace style tags with link rel='stylesheet' href='main.css' in HTML head
Reload any site page in the browser to see the centered logo—notice how this single change improves the site's professional appearance.
This demonstrates the power of external stylesheets: one modification instantly updates every linked page. Now let's apply the same centering treatment to the navigation.
Add text-align to the nav rule:
nav {
margin-bottom: 20px;
text-align: center;
}Although images aren't text, they are inline elements. The text-align property works on all inline elements including text, anchor tags, and images.
CSS Centering Techniques
Text-Align Center
Centers inline elements like images and text within their container. Applied to parent element.
Margin Auto
Centers block elements by setting left and right margins to auto. Requires defined width.
To center an element, set a width for the element and then specify the margins on the left and the right to be auto
All major browsers render the body element with approximately 8px of margin by default. Remove this with margin: 0 for full-width designs.
Optimizing CSS with Multiple Selectors
Identify common properties
Find CSS properties shared between multiple elements like h1 and h2
Create combined selector
Use comma-separated selectors: h1, h2 { shared-properties }
Remove duplicated code
Delete repeated properties from individual selectors to reduce code
Key Takeaways
