Introduction to CSS
CSS (Cascading Style Sheets) is a style sheet language used for describing 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 Timeline
- 1994 - HÃ¥kon Wium Lie proposes the concept of CSS
- 1996 - CSS Level 1 becomes a W3C Recommendation
- 1998 - CSS Level 2 is published
- 2011 - CSS Level 2 Revision 1 (CSS 2.1) becomes a W3C Recommendation
- 2011-Present - CSS Level 3 (CSS3) modules are developed and published
- Present - CSS Level 4 modules are in development
CSS has evolved from a simple styling language to a powerful tool for creating complex layouts and animations. Modern CSS includes features like flexbox, grid, custom properties (variables), and animations, making it possible to create sophisticated designs without relying on JavaScript or other technologies.
How CSS Works
CSS works by selecting HTML elements and applying styles to them. The browser reads the CSS, identifies the elements that match the selectors, and applies the corresponding styles.
selector {
property: value;
property: value;
property: value;
}
CSS follows a cascading order, which means that styles can be inherited from parent elements, and multiple style rules can apply to the same element. When conflicts occur, the cascade, specificity, and source order determine which styles are applied.
CSS, HTML, and JavaScript
While HTML provides the structure of a web page and JavaScript adds interactivity, CSS is responsible for the presentation and layout. Together, these three technologies form the foundation of modern web development:
- HTML - Structure and content
- CSS - Presentation and layout
- JavaScript - Behavior and interactivity
CSS Basics
Before diving into the details, let's understand the basic concepts of CSS.
CSS Syntax
A CSS rule consists of a selector and a declaration block. The selector points to the HTML element you want to style. The declaration block contains one or more declarations separated by semicolons.
selector {
property: value; /* This is a declaration */
property: value;
property: value;
}
Ways to Include CSS
There are three ways to include CSS in an HTML document:
1. External CSS
With an external style sheet, you can change the look of an entire website by changing just one file. Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.
<head>
<link rel="stylesheet" href="styles.css">
</head>
2. Internal CSS
An internal style sheet may be used if one single HTML page has a unique style. The internal style is defined inside the <style>
element, inside the head section.
<head>
<style>
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
</style>
</head>
3. Inline CSS
An inline style may be used to apply a unique style for a single element. To use inline styles, add the style attribute to the relevant element. The style attribute can contain any CSS property.
<h1 style="color: blue; text-align: center;">This is a heading</h1>
CSS Comments
Comments are used to explain your code, and may help when you edit the source code at a later date. Comments are ignored by browsers.
/* This is a single-line comment */
/* This is
a multi-line
comment */
CSS Versions
CSS has evolved over the years, with CSS3 being the latest major version. Unlike its predecessors, CSS3 is divided into modules, each addressing a specific aspect of styling.
Key CSS3 Modules
- Selectors
- Box Model
- Backgrounds and Borders
- Text Effects
- 2D/3D Transformations
- Animations
- Multiple Column Layout
- User Interface
For more detailed information on CSS basics, visit our CSS Basics page.
CSS Selectors
CSS selectors are patterns used to select the HTML elements you want to style. They are the bridge between your HTML document and your style sheet.
Basic Selectors
Selector | Example | Description |
---|---|---|
Element Selector | p { } |
Selects all <p> elements |
ID Selector | #navbar { } |
Selects the element with id="navbar" |
Class Selector | .intro { } |
Selects all elements with class="intro" |
Universal Selector | * { } |
Selects all elements |
Grouping Selector | h1, h2, p { } |
Selects all <h1>, <h2>, and <p> elements |
Combinators
Combinators explain the relationship between selectors.
Combinator | Example | Description |
---|---|---|
Descendant Selector (space) | div p { } |
Selects all <p> elements inside <div> elements |
Child Selector (>) | div > p { } |
Selects all <p> elements that are direct children of a <div> element |
Adjacent Sibling Selector (+) | div + p { } |
Selects the first <p> element that is placed immediately after <div> elements |
General Sibling Selector (~) | div ~ p { } |
Selects all <p> elements that are siblings of <div> elements |
Pseudo-classes
A pseudo-class is used to define a special state of an element.
Pseudo-class | Example | Description |
---|---|---|
:hover |
a:hover { } |
Selects links on mouse over |
:active |
a:active { } |
Selects the active link |
:focus |
input:focus { } |
Selects the input element which has focus |
:first-child |
p:first-child { } |
Selects every <p> element that is the first child of its parent |
:last-child |
p:last-child { } |
Selects every <p> element that is the last child of its parent |
:nth-child(n) |
p:nth-child(2) { } |
Selects every <p> element that is the second child of its parent |
:not(selector) |
:not(p) { } |
Selects every element that is not a <p> element |
Pseudo-elements
A CSS pseudo-element is used to style specified parts of an element.
Pseudo-element | Example | Description |
---|---|---|
::first-line |
p::first-line { } |
Selects the first line of every <p> element |
::first-letter |
p::first-letter { } |
Selects the first letter of every <p> element |
::before |
p::before { } |
Insert content before every <p> element |
::after |
p::after { } |
Insert content after every <p> element |
::selection |
::selection { } |
Selects the portion of an element that is selected by a user |
Attribute Selectors
Attribute selectors select elements based on an attribute or attribute value.
Selector | Example | Description |
---|---|---|
[attribute] |
[target] { } |
Selects all elements with a target attribute |
[attribute=value] |
[target="_blank"] { } |
Selects all elements with target="_blank" |
[attribute~=value] |
[title~="flower"] { } |
Selects all elements with a title attribute containing the word "flower" |
[attribute|=value] |
[lang|="en"] { } |
Selects all elements with a lang attribute value starting with "en" |
[attribute^=value] |
[class^="box"] { } |
Selects all elements with a class attribute value beginning with "box" |
[attribute$=value] |
[class$="test"] { } |
Selects all elements with a class attribute value ending with "test" |
[attribute*=value] |
[class*="te"] { } |
Selects all elements with a class attribute value containing "te" |
Specificity
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied. Specificity is based on the matching rules which are composed of different sorts of CSS selectors.
Specificity Hierarchy
Specificity is calculated as a four-part value: a, b, c, d
- a: Inline styles (style attribute)
- b: Number of ID selectors
- c: Number of class selectors, attribute selectors, and pseudo-classes
- d: Number of element selectors and pseudo-elements
/* Specificity: 0,0,0,1 */
p {
color: red;
}
/* Specificity: 0,0,1,0 */
.text {
color: blue;
}
/* Specificity: 0,1,0,0 */
#content {
color: green;
}
/* Specificity: 1,0,0,0 */
<p style="color: yellow;">Inline style</p>
In the example above, the inline style has the highest specificity and will override all other styles. The ID selector has the second highest specificity, followed by the class selector, and finally the element selector.
CSS Box Model
The CSS box model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.
Box Model Components
- Content - The content of the box, where text and images appear
- Padding - Clears an area around the content (inside the box)
- Border - A border that goes around the padding and content
- Margin - Clears an area outside the border (outside the box)
div {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 30px;
}
(width: 200px)
Box Sizing
The box-sizing
property defines how the width and height of an element are calculated: should they include padding and borders, or not.
/* Default box-sizing */
.box-content {
box-sizing: content-box;
width: 300px;
padding: 20px;
border: 5px solid black;
}
/* Alternative box-sizing */
.box-border {
box-sizing: border-box;
width: 300px;
padding: 20px;
border: 5px solid black;
}
content-box (default):
(width: 200px)
border-box:
(width: 150px)
Margin Collapse
Margin collapse occurs when the top and bottom margins of blocks are combined into a single margin equal to the largest individual margin.
.box1 {
margin-bottom: 30px;
}
.box2 {
margin-top: 20px;
}
The margin between these two boxes is 30px (not 50px) due to margin collapse:
CSS Layout
CSS provides several techniques for controlling the layout of a web page. The most common ones are Flexbox, Grid, and positioning.
Flexbox
Flexbox is a one-dimensional layout method for laying out items in rows or columns. It's ideal for components and small-scale layouts.
.container {
display: flex;
flex-direction: row; /* or column */
justify-content: space-between; /* horizontal alignment */
align-items: center; /* vertical alignment */
flex-wrap: wrap; /* allow items to wrap */
}
.item {
flex: 1; /* grow and shrink equally */
}
Grid
Grid is a two-dimensional layout system designed for laying out complex web pages. It allows you to define rows and columns and place items precisely within them.
.container {
display: grid;
grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
grid-template-rows: 100px 200px; /* 2 rows with specific heights */
gap: 10px; /* gap between grid items */
}
.item1 {
grid-column: 1 / 3; /* span from column line 1 to 3 */
grid-row: 1; /* place in row 1 */
}
Positioning
The position
property specifies the type of positioning method used for an element.
Value | Description |
---|---|
static |
Default. Elements are positioned according to the normal flow of the document. |
relative |
The element is positioned relative to its normal position. |
absolute |
The element is positioned relative to the nearest positioned ancestor. |
fixed |
The element is positioned relative to the viewport. |
sticky |
The element is positioned based on the user's scroll position. |
.relative {
position: relative;
top: 20px;
left: 20px;
}
.absolute {
position: absolute;
top: 20px;
right: 20px;
}
.fixed {
position: fixed;
bottom: 20px;
right: 20px;
}
Float
The float
property specifies whether an element should float to the left, right, or not at all. It's often used for wrapping text around images.
.float-left {
float: left;
margin-right: 10px;
}
.float-right {
float: right;
margin-left: 10px;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
Display
The display
property specifies the display behavior of an element.
Value | Description |
---|---|
block |
Displays an element as a block element (like paragraphs and headers). |
inline |
Displays an element as an inline element (like spans). |
inline-block |
Displays an element as an inline-level block container. |
none |
The element is completely removed from the page. |
flex |
Displays an element as a block-level flex container. |
grid |
Displays an element as a block-level grid container. |
CSS Typography
Typography is the art and technique of arranging type to make written language legible, readable, and appealing when displayed. CSS provides various properties to control typography.
Font Properties
Property | Description | Example |
---|---|---|
font-family |
Specifies the font for text | font-family: Arial, sans-serif; |
font-size |
Specifies the size of text | font-size: 16px; |
font-weight |
Specifies the weight (boldness) of text | font-weight: bold; |
font-style |
Specifies the style of text | font-style: italic; |
font-variant |
Specifies whether text should be displayed in small-caps | font-variant: small-caps; |
line-height |
Specifies the height of a line | line-height: 1.5; |
font |
Shorthand property for setting all font properties | font: italic bold 16px/1.5 Arial, sans-serif; |
Text Properties
Property | Description | Example |
---|---|---|
color |
Sets the color of text | color: blue; |
text-align |
Specifies the horizontal alignment of text | text-align: center; |
text-decoration |
Specifies the decoration added to text | text-decoration: underline; |
text-transform |
Controls the capitalization of text | text-transform: uppercase; |
text-indent |
Specifies the indentation of the first line of text | text-indent: 50px; |
letter-spacing |
Increases or decreases the space between characters | letter-spacing: 2px; |
word-spacing |
Increases or decreases the space between words | word-spacing: 4px; |
white-space |
Specifies how white-space inside an element is handled | white-space: nowrap; |
Web Fonts
Web fonts allow you to use fonts that are not installed on the user's computer. You can use web fonts by linking to a font file or using a font service like Google Fonts.
/* Using @font-face */
@font-face {
font-family: 'MyFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
font-weight: normal;
font-style: normal;
}
/* Using Google Fonts */
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');
body {
font-family: 'Roboto', sans-serif;
}
Font Stacks
A font stack is a list of fonts in the font-family
property. The browser will use the first font in the list that is available on the user's computer.
/* Serif font stack */
body {
font-family: Georgia, Times, "Times New Roman", serif;
}
/* Sans-serif font stack */
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
/* Monospace font stack */
code {
font-family: "Courier New", Courier, monospace;
}
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 CSS styles depending on the device characteristics, such as screen width, height, orientation, or resolution.
/* Base styles for all devices */
body {
font-size: 16px;
}
/* Styles for screens wider than 768px */
@media screen and (min-width: 768px) {
body {
font-size: 18px;
}
}
/* Styles for screens wider than 1200px */
@media screen and (min-width: 1200px) {
body {
font-size: 20px;
}
}
/* Styles for print */
@media print {
body {
font-size: 12pt;
}
}
Viewport Meta Tag
The viewport meta tag tells the browser how to control the page's dimensions and scaling. It's essential for responsive design.
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Responsive Units
Responsive units allow elements to scale relative to the viewport or parent element.
Unit | Description |
---|---|
% |
Relative to the parent element |
em |
Relative to the font-size of the element |
rem |
Relative to the font-size of the root element |
vw |
Relative to 1% of the viewport width |
vh |
Relative to 1% of the viewport height |
vmin |
Relative to 1% of the viewport's smaller dimension |
vmax |
Relative to 1% of the viewport's larger dimension |
Responsive Images
Responsive images automatically adjust to fit the size of the screen.
/* CSS approach */
img {
max-width: 100%;
height: auto;
}
/* HTML approach with srcset */
<img src="small.jpg"
srcset="medium.jpg 1000w, large.jpg 2000w"
sizes="(max-width: 500px) 100vw, (max-width: 1500px) 50vw, 800px"
alt="Responsive Image">
/* HTML approach with picture */
<picture>
<source media="(min-width: 1000px)" srcset="large.jpg">
<source media="(min-width: 600px)" srcset="medium.jpg">
<img src="small.jpg" alt="Responsive Image">
</picture>
Mobile-First Design
Mobile-first design is an approach where you design for mobile devices first, then progressively enhance the design for larger screens.
/* Base styles for mobile devices */
.container {
display: flex;
flex-direction: column;
}
/* Styles for tablets and larger */
@media screen and (min-width: 768px) {
.container {
flex-direction: row;
}
}
CSS Animations and Transitions
CSS provides two main ways to create animations: transitions and keyframe animations.
Transitions
Transitions allow you to change property values smoothly over a given duration.
.button {
background-color: blue;
color: white;
padding: 10px 20px;
transition: background-color 0.3s ease;
}
.button:hover {
background-color: darkblue;
}
Keyframe Animations
Keyframe animations allow you to create more complex animations by defining keyframes at various points in the animation sequence.
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.fade-in {
animation: fadeIn 1s ease-in-out;
}
@keyframes pulse {
0% {
transform: scale(1);
}
50% {
transform: scale(1.1);
}
100% {
transform: scale(1);
}
}
.pulse {
animation: pulse 2s infinite;
}
Animation Properties
Property | Description |
---|---|
animation-name |
Specifies the name of the @keyframes animation |
animation-duration |
Specifies how long the animation should take to complete one cycle |
animation-timing-function |
Specifies the speed curve of the animation |
animation-delay |
Specifies a delay before the animation starts |
animation-iteration-count |
Specifies the number of times the animation should be played |
animation-direction |
Specifies whether the animation should play in reverse on alternate cycles |
animation-fill-mode |
Specifies what values are applied by the animation outside the time it is executing |
animation-play-state |
Specifies whether the animation is running or paused |
animation |
Shorthand property for setting all animation properties |
Transition Properties
Property | Description |
---|---|
transition-property |
Specifies the name of the CSS property the transition effect is for |
transition-duration |
Specifies how long the transition effect takes to complete |
transition-timing-function |
Specifies the speed curve of the transition effect |
transition-delay |
Specifies a delay before the transition effect starts |
transition |
Shorthand property for setting all transition properties |
Transforms
The transform
property applies a 2D or 3D transformation to an element. It allows you to rotate, scale, move, or skew elements.
/* 2D Transforms */
.rotate {
transform: rotate(45deg);
}
.scale {
transform: scale(1.5);
}
.translate {
transform: translate(50px, 100px);
}
.skew {
transform: skew(20deg, 10deg);
}
/* 3D Transforms */
.rotate3d {
transform: rotateX(45deg) rotateY(45deg) rotateZ(45deg);
}
.translate3d {
transform: translate3d(50px, 100px, 200px);
}
/* Multiple transforms */
.multiple {
transform: rotate(45deg) scale(1.5) translate(50px, 100px);
}
CSS Best Practices
Following best practices ensures that your CSS code is maintainable, efficient, and performs well.
Organization
- Use a consistent naming convention (e.g., BEM, SMACSS, OOCSS)
- Group related styles together
- Use comments to explain complex code
- Split your CSS into multiple files for large projects
- Use a preprocessor like Sass or Less for large projects
Performance
- Minimize the use of expensive properties (e.g., box-shadow, border-radius, opacity)
- Use shorthand properties when possible
- Avoid using !important
- Minimize the use of descendant selectors
- Use efficient selectors (ID and class selectors are faster than tag selectors)
- Minify your CSS for production
Maintainability
- Use meaningful class names
- Avoid inline styles
- Use CSS variables for repeated values
- Keep your selectors as simple as possible
- Use a reset or normalize CSS
- Follow a consistent indentation and formatting style
Accessibility
- Ensure sufficient color contrast
- Don't rely solely on color to convey information
- Use relative units (em, rem) for font sizes
- Ensure focus states are visible
- Test with screen readers and keyboard navigation
Browser Compatibility
- Use vendor prefixes for experimental properties
- Test your CSS in multiple browsers
- Use feature detection or polyfills for unsupported features
- Consider using a tool like Autoprefixer
CSS Methodologies
CSS methodologies are structured approaches to writing CSS that help keep your code organized and maintainable.
BEM (Block, Element, Modifier)
/* Block */
.card { }
/* Element */
.card__title { }
.card__image { }
.card__content { }
/* Modifier */
.card--featured { }
.card__title--large { }
SMACSS (Scalable and Modular Architecture for CSS)
/* Base */
body, h1, h2, p { }
/* Layout */
.l-header, .l-sidebar, .l-content { }
/* Module */
.card, .button, .nav { }
/* State */
.is-active, .is-hidden { }
/* Theme */
.theme-dark, .theme-light { }
OOCSS (Object-Oriented CSS)
/* Structure */
.card {
border: 1px solid #ddd;
border-radius: 4px;
}
/* Skin */
.card-primary {
background-color: #f0f0f0;
color: #333;
}
/* Usage */
<div class="card card-primary"></div>
Additional Resources
Here are some valuable resources for learning more about CSS:
Documentation
Tutorials and Guides
- W3Schools CSS Tutorial
- MDN Learn CSS
- Flexbox Froggy - A game for learning Flexbox
- Grid Garden - A game for learning CSS Grid
Tools
- Can I Use - Browser support tables for CSS features
- Autoprefixer - Add vendor prefixes to CSS
- CSS Gradient - CSS gradient generator
- Clippy - CSS clip-path maker
Books
- "CSS: The Definitive Guide" by Eric Meyer and Estelle Weyl
- "CSS Secrets" by Lea Verou
- "CSS in Depth" by Keith J. Grant