CSS Introduction & Syntax: The Art of Styling Webpages
What is CSS?
CSS (Cascading Style Sheets) is a language used to describe the style of HTML documents. If HTML is the skeleton of a webpage, then CSS is the appearance and clothing of the webpage, determining its visual presentation such as colors, fonts, layouts, and animations.
Imagine decorating a house:
- HTML is like the structure of the house (walls, doors, windows, room divisions).
- CSS is like the interior design (wall colors, furniture placement, decoration style).
/* CSS Rule Example */
h1 {
color: #2c3e50; /* Text color: dark blue-gray */
font-size: 2.5rem; /* Font size: 2.5 times root font size */
text-align: center; /* Text center aligned */
margin-bottom: 20px; /* Bottom margin: 20px */
}
p {
line-height: 1.6; /* Line height: 1.6 times font size */
color: #333; /* Text color: dark gray */
}Core Functions of CSS
1. Separation of Content and Presentation
CSS achieves the separation of webpage content and visual presentation, which is one of the core concepts of modern Web development:
<!-- HTML is responsible for structure and content -->
<article class="blog-post">
<h1>Article Title</h1>
<p>This is the content paragraph of the article...</p>
</article>/* CSS is responsible for style and presentation */
.blog-post {
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.blog-post h1 {
color: #2c3e50;
border-bottom: 3px solid #3498db;
padding-bottom: 10px;
}2. Cascading Nature
The "Cascading" nature of CSS allows multiple style rules to apply to the same element, and determines the final style according to specific priority rules:
/* Multiple style rules can apply to the same element */
p {
color: blue; /* Base style */
font-size: 16px; /* Base style */
}
.article-content p {
color: #333; /* More specific style, will override the blue above */
}
.article-content p.important {
color: red; /* Most specific style, highest priority */
font-weight: bold;
}History of CSS Development
Early Exploration (1994-1996)
The birth of CSS stemmed from the need for webpage beautification. In the early days, webpage styles were mainly controlled through HTML tag attributes, which had many problems:
<!-- Early inline style method (not recommended) -->
<h1><font color="red" size="6" face="Arial">Title</font></h1>
<p><font color="blue" size="3">Paragraph text</font></p>Key Milestones:
- 1994: Håkon Wium Lie proposed the initial concept of CSS.
- 1996: CSS Level 1 became a W3C Recommendation.
- 1998: CSS Level 2 was published.
CSS 2.1 Maturity Period (1998-2011)
CSS 2.1 became the most stable and widely supported version, introducing important features like positioning, floating, and table layout:
/* Classic features of CSS 2.1 */
.container {
position: relative; /* Relative positioning */
width: 100%;
max-width: 1200px;
margin: 0 auto;
}
.sidebar {
position: absolute; /* Absolute positioning */
right: 0;
top: 0;
width: 250px;
}
.main-content {
margin-right: 270px; /* Leave space for sidebar */
}
.float-element {
float: left; /* Float layout */
width: 50%;
margin-right: 20px;
}
.clearfix::after {
content: "";
display: table;
clear: both; /* Clear float */
}CSS 3 Revolution Era (2009-Present)
CSS 3 adopted modular development, allowing individual functional modules to develop independently. This period introduced many revolutionary features:
Flexbox
.flex-container {
display: flex; /* Flex container */
justify-content: space-between; /* Main axis alignment */
align-items: center; /* Cross axis alignment */
gap: 20px; /* Gap */
}
.flex-item {
flex: 1; /* Flex grow/shrink */
min-width: 0; /* Prevent overflow */
}Grid Layout
.grid-container {
display: grid; /* Grid container */
grid-template-columns: 1fr 2fr 1fr; /* Column definition */
grid-template-rows: auto 1fr auto; /* Row definition */
gap: 20px; /* Grid gap */
}
.grid-item {
grid-column: span 2; /* Span columns */
grid-row: 1 / 3; /* Span rows */
}CSS Variables
:root {
--primary-color: #3498db; /* CSS variable definition */
--secondary-color: #2ecc71;
--spacing-unit: 8px;
--border-radius: 4px;
}
.button {
background: var(--primary-color);
padding: calc(var(--spacing-unit) * 2);
border-radius: var(--border-radius);
}CSS Syntax Structure
Basic Syntax Rules
CSS rules consist of selectors and declaration blocks:
/* Selector Declaration Block */
/* | | */
/* v v */
h1 {
/* Selector: Selects the element to apply style to */
color: blue; /* Declaration: Property: Value */
font-size: 24px; /* Declaration: Property: Value */
margin: 10px 0; /* Declaration: Property: Value */
} /* End of declaration block */Types of Selectors
1. Basic Selectors
/* Element selector */
h1 {
color: blue;
}
/* Class selector */
.highlight {
background: yellow;
}
/* ID selector */
#header {
position: fixed;
top: 0;
}
/* Universal selector */
* {
box-sizing: border-box;
}2. Combinators
/* Descendant selector */
.container p {
margin: 15px 0;
}
/* Child selector */
.menu > li {
display: inline-block;
}
/* Adjacent sibling selector */
h1 + p {
font-weight: bold;
}
/* Attribute selector */
input[type="text"] {
border: 1px solid #ccc;
}3. Pseudo-class and Pseudo-element Selectors
/* Pseudo-class selector */
a:hover {
color: red;
}
a:active {
transform: scale(0.95);
}
li:nth-child(odd) {
background: #f9f9f9;
}
/* Pseudo-element selector */
p::first-line {
font-weight: bold;
}
.button::before {
content: "★ ";
}Properties and Values
CSS properties control various visual characteristics of elements:
.text-styling {
/* Font related */
font-family: "Helvetica Neue", Arial, sans-serif;
font-size: 16px;
font-weight: 500;
line-height: 1.5;
color: #333;
text-align: justify;
/* Background and border */
background-color: #fff;
background-image: url("pattern.png");
border: 1px solid #ddd;
border-radius: 8px;
/* Padding and margin */
padding: 20px;
margin: 15px 0;
/* Size and positioning */
width: 100%;
height: auto;
max-width: 600px;
position: relative;
}CSS Cascading and Inheritance
Cascading Rules
When multiple CSS rules apply to the same element, the browser determines the final style according to the following rules:
- Importance:
!importantdeclarations have the highest priority. - Specificity: The more specific the selector, the higher the priority.
- Source Order: Rules defined later override rules defined earlier.
/* Specificity Example */
p {
color: gray;
} /* Specificity: 0,0,0,1 */
p.content {
color: black;
} /* Specificity: 0,0,1,1 */
div article p.content {
color: blue;
} /* Specificity: 0,0,1,3 */
#main p.content {
color: red;
} /* Specificity: 0,1,1,1 */
p.important {
color: green !important;
} /* Highest priority */Inheritance Mechanism
Certain CSS properties are automatically inherited from parent elements to child elements:
/* Inheritable properties */
body {
font-family: Arial, sans-serif; /* Child elements will inherit font */
color: #333; /* Child elements will inherit text color */
line-height: 1.6; /* Child elements will inherit line height */
}
/* Non-inheritable properties */
body {
margin: 0; /* Child elements will not inherit margin */
padding: 0; /* Child elements will not inherit padding */
border: none; /* Child elements will not inherit border */
background: white; /* Child elements will not inherit background */
}Ways to Include CSS
1. Inline Styles
Defining styles directly in HTML tags (not recommended for extensive use):
<h1 style="color: blue; font-size: 24px;">Title</h1>
<p style="margin: 15px 0;">Paragraph content</p>2. Internal Style Sheets
Defining styles in the <head> section of an HTML document:
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
line-height: 1.6;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
</style>
</head>
<body>
<!-- Page content -->
</body>
</html>3. External Style Sheets (Recommended)
Defining styles in independent CSS files:
/* styles.css */
body {
font-family: "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
color: #333;
margin: 0;
padding: 0;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<!-- Page content -->
</body>
</html>Modern CSS Features
1. CSS Variables (Custom Properties)
CSS variables make styles more flexible and maintainable:
:root {
/* Define global variables */
--primary-color: #3498db;
--secondary-color: #2ecc71;
--text-color: #2c3e50;
--bg-color: #ecf0f1;
--border-radius: 8px;
--spacing-sm: 8px;
--spacing-md: 16px;
--spacing-lg: 24px;
}
.card {
background: var(--bg-color);
border-radius: var(--border-radius);
padding: var(--spacing-md);
margin-bottom: var(--spacing-lg);
}
.card-title {
color: var(--primary-color);
margin-bottom: var(--spacing-sm);
}
/* JavaScript can dynamically modify CSS variables */
/* document.documentElement.style.setProperty('--primary-color', '#e74c3c'); */2. Responsive Design
Media queries allow webpages to adapt to different devices and screen sizes:
/* Mobile-first responsive design */
.container {
width: 100%;
padding: 0 15px;
margin: 0 auto;
}
/* Tablet devices */
@media (min-width: 768px) {
.container {
max-width: 750px;
padding: 0 30px;
}
}
/* Desktop devices */
@media (min-width: 1024px) {
.container {
max-width: 970px;
padding: 0 40px;
}
}
/* Large screen devices */
@media (min-width: 1200px) {
.container {
max-width: 1170px;
}
}3. CSS Grid and Flexbox
Modern layout technologies make complex layouts simple:
/* Flexbox for component internal layout */
.nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
.nav-item {
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.nav-item:hover {
background-color: rgba(255, 255, 255, 0.1);
}
/* Grid for overall page layout */
.page-layout {
display: grid;
grid-template-areas:
"header header"
"sidebar main"
"footer footer";
grid-template-columns: 250px 1fr;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
gap: 20px;
}
.header {
grid-area: header;
}
.sidebar {
grid-area: sidebar;
}
.main {
grid-area: main;
}
.footer {
grid-area: footer;
}CSS Best Practices
1. Naming Conventions
Use clear class names and structured naming conventions:
/* BEM Naming Methodology */
.card {
} /* Block */
.card__title {
} /* Block__Element */
.card__content {
} /* Block__Element */
.card--featured {
} /* Block--Modifier */
.card__title--large {
} /* Block__Element--Modifier */
/* Functional naming */
.text-center {
text-align: center;
}
.mb-0 {
margin-bottom: 0;
}
.p-4 {
padding: 1rem;
}
.hidden {
display: none;
}2. Code Organization
Keep CSS code clear and maintainable:
/* ==========================================================================
Base Styles
========================================================================== */
/* Reset */
*,
*::before,
*::after {
box-sizing: border-box;
}
/* Typography */
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
line-height: 1.6;
color: #333;
}
/* ==========================================================================
Component Styles
========================================================================== */
/* Buttons */
.btn {
display: inline-block;
padding: 12px 24px;
border: none;
border-radius: 4px;
cursor: pointer;
transition: all 0.3s ease;
}
.btn--primary {
background: #3498db;
color: white;
}
.btn--primary:hover {
background: #2980b9;
transform: translateY(-2px);
}3. Performance Optimization
Write efficient CSS code:
/* Avoid excessive nesting */
/* Not recommended */
.container .header .nav .menu .item .link {
}
/* Recommended */
.nav-link {
}
/* Use efficient properties */
/* Recommended */
transform: translateX(20px);
/* Not recommended (triggers reflow) */
left: 20px;
/* Use !important reasonably */
/* Avoid */
.text {
color: red !important;
}
/* Use in special cases */
.modal-overlay {
z-index: 9999 !important; /* Ensure modal is always on top */
}Summary
CSS is an indispensable technology in frontend development. It is not just about adding colors and styles to webpages, but also a key tool for implementing complex layouts, interactive animations, and responsive designs.
Key Points Review:
- CSS stands for Cascading Style Sheets and is responsible for the visual presentation of webpages.
- CSS achieves the separation of content and presentation, improving code maintainability.
- The cascading nature of CSS determines the priority of multiple style rules.
- Modern CSS 3 provides powerful layout tools (Flexbox, Grid) and animation capabilities.
- CSS variables and responsive design make styles more flexible and adaptable.
- Good CSS coding standards and code organization are crucial for project maintenance.
Mastering the basic syntax and core concepts of CSS is the foundation for building beautiful, modern web applications.