CSS Tutorial: Styling Your Web Pages
Learn how to style your HTML with CSS (Cascading Style Sheets) to create beautiful, responsive, and interactive web pages.
Introduction to CSS
CSS (Cascading Style Sheets) is a stylesheet language used to describe the presentation of a document written in HTML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.
CSS is one of the core languages of the web and is standardized across browsers according to the W3C specification. With CSS, you can control the color, font, size, spacing, and many other aspects of HTML elements.
Quick Tip
CSS works by associating rules with HTML elements. These rules govern how the content of specified elements should be displayed.
Why Use CSS?
CSS allows you to:
- Control the layout of multiple web pages all at once
- Apply different styles to different media types (screens, printers, etc.)
- Create responsive designs that adapt to different screen sizes
- Animate elements and create interactive effects
- Separate content (HTML) from presentation (CSS) for better maintainability
Before CSS, HTML documents included both content and styling information, making them larger and more complex. With CSS, the styling information can be kept in separate files, making HTML files cleaner and CSS reusable across multiple pages.
CSS Syntax
CSS consists of a selector and a declaration block. The selector points to the HTML element you want to style, and the declaration block contains one or more declarations separated by semicolons.
selector { property: value; property: value; }
Selectors
A selector is the part of a CSS rule that determines which HTML elements the rule will apply to. Selectors can target elements based on their type, class, ID, attributes, and more.
/* Element selector */ h1 { color: blue; } /* Class selector */ .highlight { background-color: yellow; } /* ID selector */ #header { font-size: 24px; }
Properties & Values
CSS properties are the aspects of an element that you want to style, such as color, font, width, height, etc. Each property is assigned a value, which specifies how you want to change that aspect.
p { color: red; /* Text color */ font-size: 16px; /* Text size */ font-family: 'Arial', sans-serif; /* Font type */ background-color: lightgray; /* Background color */ padding: 10px; /* Space inside the element */ margin: 20px; /* Space outside the element */ }
Adding CSS to HTML
There are three ways to add CSS to an HTML document: inline, internal, and external.
Inline CSS
Inline CSS is used to apply a unique style to a single HTML element using the style attribute.
<p style="color: blue; font-size: 18px;">This is a paragraph with inline CSS</p>
Result:
This is a paragraph with inline CSS
Important Note
Inline CSS should be used sparingly as it mixes content with presentation, making the code harder to maintain. It's generally better to use external or internal CSS.
Internal CSS
Internal CSS is defined in the <style> element, inside the <head> section of an HTML page.
<head> <style> body { background-color: lightblue; } h1 { color: navy; margin-left: 20px; } </style> </head>
External CSS
External CSS is defined in a separate file with a .css extension. This is the most common and preferred way to style a website as it separates HTML and CSS, making the code easier to maintain.
/* styles.css */ body { background-color: lightblue; } h1 { color: navy; margin-left: 20px; }
To link the external CSS file to your HTML document, add a <link> element in the <head> section:
<head> <link rel="stylesheet" href="styles.css"> </head>
Quick Tip
External CSS files can be cached by browsers, which can reduce page load times for repeat visitors to your site.
CSS Colors
Colors are a fundamental aspect of web design. CSS provides several ways to define colors, each with its own advantages and use cases.
Color Values in CSS
CSS supports various color formats:
/* Color Keywords */ h1 { color: red; } /* Hexadecimal Colors */ h2 { color: #ff0000; /* Same as red */ } /* Short Hexadecimal */ h3 { color: #f00; /* Same as #ff0000 */ } /* RGB Colors */ p { color: rgb(255, 0, 0); /* Same as red */ } /* RGBA Colors (with alpha/transparency) */ div { background-color: rgba(255, 0, 0, 0.5); /* Semi-transparent red */ } /* HSL Colors (Hue, Saturation, Lightness) */ span { color: hsl(0, 100%, 50%); /* Same as red */ } /* HSLA Colors (with alpha/transparency) */ button { background-color: hsla(0, 100%, 50%, 0.5); /* Semi-transparent red */ }
Color Accessibility
When choosing colors, ensure there's sufficient contrast between text and background colors for readability. The Web Content Accessibility Guidelines (WCAG) recommend a contrast ratio of at least 4.5:1 for normal text and 3:1 for large text.
CSS Variables for Colors
CSS variables (custom properties) are excellent for managing colors in your project:
:root { --primary-color: #4f46e5; --secondary-color: #10b981; --text-color: #1f2937; --background-color: #ffffff; } body { background-color: var(--background-color); color: var(--text-color); } button { background-color: var(--primary-color); color: white; }
CSS Box Model
The CSS Box Model is fundamental to layout in CSS. It describes how elements are rendered as rectangular boxes with content, padding, border, and margin areas.
Box Model Components
Every element in a web page is a rectangular box consisting of:
- Content: The actual content of the box where text and images appear
- Padding: The space between the content and the border
- Border: A line that surrounds the padding (if any) and content
- Margin: The space outside the border, separating the element from other elements
Margin
The margin property creates space around elements, outside of any defined borders.
/* Apply to all four sides */ div { margin: 10px; } /* Apply to top/bottom and right/left */ div { margin: 10px 20px; } /* Apply to top, right/left, and bottom */ div { margin: 10px 20px 30px; } /* Apply to top, right, bottom, and left */ div { margin: 10px 20px 30px 40px; } /* Individual sides */ div { margin-top: 10px; margin-right: 20px; margin-bottom: 30px; margin-left: 40px; }
Margin Collapse
Vertical margins between adjacent elements can collapse, meaning the larger of the two margins is used while the smaller one is ignored. This only happens with vertical (top and bottom) margins, not horizontal ones.
Border
The border property adds a border around an element.
/* Shorthand */ div { border: 1px solid black; } /* Individual properties */ div { border-width: 1px; border-style: solid; border-color: black; } /* Individual sides */ div { border-top: 1px solid red; border-right: 2px dashed green; border-bottom: 3px dotted blue; border-left: 4px double orange; } /* Border radius (rounded corners) */ div { border-radius: 10px; } /* Individual corner radii */ div { border-top-left-radius: 10px; border-top-right-radius: 20px; border-bottom-right-radius: 30px; border-bottom-left-radius: 40px; }
Padding
The padding property creates space around an element's content, inside of any defined borders.
/* Apply to all four sides */ div { padding: 10px; } /* Apply to top/bottom and right/left */ div { padding: 10px 20px; } /* Apply to top, right/left, and bottom */ div { padding: 10px 20px 30px; } /* Apply to top, right, bottom, and left */ div { padding: 10px 20px 30px 40px; } /* Individual sides */ div { padding-top: 10px; padding-right: 20px; padding-bottom: 30px; padding-left: 40px; }
Box Sizing
The box-sizing property defines how the width and height of an element are calculated.
/* Default box-sizing */ .content-box { box-sizing: content-box; width: 300px; padding: 20px; border: 5px solid black; /* Total width: 300px + 40px (padding) + 10px (border) = 350px */ } /* Alternative box-sizing */ .border-box { box-sizing: border-box; width: 300px; padding: 20px; border: 5px solid black; /* Total width: 300px (padding and border included) */ }
Best Practice
Many developers prefer to use box-sizing: border-box for all elements as it makes sizing more intuitive. You can apply it globally with:
*, *::before, *::after { box-sizing: border-box; }
CSS Layout
CSS provides several powerful layout mechanisms to position and arrange elements on a web page.
Display Property
The display property specifies how an element is displayed on the page.
/* Block elements take up the full width available */ div { display: block; } /* Inline elements only take up as much width as necessary */ span { display: inline; } /* Inline-block elements are placed inline but behave like block elements */ .inline-block { display: inline-block; } /* Hidden elements */ .hidden { display: none; }
Flexbox
Flexbox is a one-dimensional layout method designed for laying out items in rows or columns.
/* Container */ .flex-container { display: flex; flex-direction: row; /* or column, row-reverse, column-reverse */ flex-wrap: wrap; /* or nowrap, wrap-reverse */ justify-content: space-between; /* or flex-start, flex-end, center, space-around, space-evenly */ align-items: center; /* or flex-start, flex-end, stretch, baseline */ gap: 10px; /* space between items */ } /* Items */ .flex-item { flex: 1; /* shorthand for flex-grow, flex-shrink, flex-basis */ align-self: center; /* overrides align-items for specific item */ }
Flexbox Example:
CSS Grid
CSS Grid is a two-dimensional layout system designed for laying out items in rows and columns simultaneously.
/* Container */ .grid-container { display: grid; grid-template-columns: repeat(3, 1fr); /* Three equal columns */ grid-template-rows: auto auto; /* Two rows, height determined by content */ gap: 10px; /* Space between grid items */ } /* Items */ .grid-item-1 { grid-column: 1 / 3; /* Span from column line 1 to 3 */ grid-row: 1; } /* Items */ .grid-item-2 { grid-column: 3; grid-row: 1 / 3; /* Span from row line 1 to 3 */ }
Grid Example:
Responsive Design
Responsive design is an approach to web design that makes web pages render well on a variety of devices and window or screen sizes.
Media Queries
Media queries allow you to apply different styles for different media types/devices.
/* Base styles for all screen sizes */ body { font-size: 16px; } /* Styles for screens smaller than 768px (mobile) */ @media (max-width: 767px) { body { font-size: 14px; } .container { width: 100%; padding: 0 15px; } } /* Styles for screens between 768px and 991px (tablet) */ @media (min-width: 768px) and (max-width: 991px) { body { font-size: 15px; } .container { width: 750px; margin: 0 auto; } } /* Styles for screens larger than 992px (desktop) */ @media (min-width: 992px) { body { font-size: 16px; } .container { width: 970px; margin: 0 auto; } }
Responsive Units
Using relative units instead of absolute units makes your design more flexible.
/* Relative units */ body { font-size: 16px; /* Base font size */ } h1 { font-size: 2em; /* 2 times the parent element's font size */ } p { font-size: 1rem; /* 1 times the root element's font size */ } .container { width: 80%; /* 80% of the parent element's width */ max-width: 1200px; /* Maximum width */ } .hero { height: 100vh; /* 100% of the viewport height */ } .sidebar { width: 20vw; /* 20% of the viewport width */ }
Transitions & Animations
CSS transitions and animations allow you to create smooth effects when changing from one style to another.
Transitions
Transitions enable you to define the transition between two states of an element.
.button { background-color: blue; color: white; padding: 10px 20px; transition: background-color 0.3s ease, transform 0.3s ease; } .button:hover { background-color: darkblue; transform: scale(1.1); }
Result (hover over the button):
Animations
CSS animations allow you to create more complex animations with keyframes.
/* Define the animation */ @keyframes pulse { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.2); opacity: 0.7; } 100% { transform: scale(1); opacity: 1; } } /* Apply the animation */ .pulse { animation-name: pulse; animation-duration: 2s; animation-timing-function: ease-in-out; animation-iteration-count: infinite; } /* Shorthand */ .pulse { animation: pulse 2s ease-in-out infinite; }
Result:
Best Practices
Following best practices ensures your CSS code is clean, maintainable, and efficient.
CSS Best Practices
- Use a consistent naming convention for classes (e.g., BEM, SMACSS)
- Organize your CSS with a clear structure
- Use comments to explain complex code
- Avoid using !important unless absolutely necessary
- Minimize the use of IDs for styling
- Use shorthand properties when possible
- Group related properties together
- Use a CSS preprocessor like Sass or Less for larger projects
- Optimize your CSS for performance
- Test your CSS across different browsers and devices
- Use CSS variables for consistent values (colors, spacing, etc.)
- Consider using a CSS framework or utility-first CSS for larger projects
/* Using CSS variables */ :root { --primary-color: #4338ca; --secondary-color: #10b981; --text-color: #1f2937; --spacing-unit: 8px; } .button { background-color: var(--primary-color); color: white; padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3); } /* Using shorthand properties */ .box { /* Instead of: */ /* margin-top: 10px; */ /* margin-right: 20px; */ /* margin-bottom: 10px; */ /* margin-left: 20px; */ /* Use: */ margin: 10px 20px; }
Practice Projects
The best way to learn CSS is by practicing. Here are some projects you can try:
CSS Practice Projects
Project 1: Responsive Navigation Bar
Create a responsive navigation bar that works well on both desktop and mobile devices:
- Design a horizontal navigation bar for desktop
- Create a hamburger menu for mobile devices
- Add smooth transitions when toggling the mobile menu
- Include hover effects for navigation links
- Make it responsive using media queries
Hint: Use Flexbox for the desktop layout and CSS transitions for the toggle effect.
Project 2: Product Card
Design a product card that could be used in an e-commerce website:
- Include a product image, title, price, and description
- Add a "Add to Cart" button with hover effects
- Create a badge for "Sale" or "New" items
- Add a subtle animation when hovering over the card
- Make it responsive for different screen sizes
Hint: Use the box-shadow property for a card-like appearance and CSS transitions for hover effects.
Project 3: Portfolio Layout
Create a responsive portfolio layout with the following features:
- A hero section with your name and a brief introduction
- A skills section with progress bars or skill cards
- A projects section with a grid of project cards
- A contact form with styled input fields
- Make it responsive using CSS Grid and/or Flexbox
Hint: Use CSS Grid for the project layout and CSS animations for interactive elements.
Comments
CSS comments are used to explain your code and are ignored by browsers. Comments start with /* and end with */.