CSS (Cascading Style Sheets)
Definition
CSS (Cascading Style Sheets) is a style sheet language used to describe the presentation and formatting of documents written in HTML. CSS separates the content of a webpage (HTML) from its visual presentation, allowing developers to control layout, colors, fonts, spacing, animations, and other visual aspects of web pages.
The term "Cascading" refers to the way style rules are applied to elements, with multiple style rules potentially applying to the same element based on specificity, inheritance, and the order of declaration.
The Role of CSS in Web Development
CSS serves several crucial functions in web development:
-
Separation of Concerns: CSS separates presentation from content, allowing HTML to focus on structure and content while CSS handles the visual styling.
-
Consistency: CSS enables consistent styling across multiple pages of a website.
-
Efficiency: Styles can be defined once and applied to multiple elements, reducing redundancy and file size.
-
Responsiveness: CSS allows websites to adapt to different screen sizes and devices.
-
Accessibility: Proper CSS implementation can improve readability and usability for all users.
CSS Syntax
CSS consists of a series of rules. Each rule has two main parts: a selector and a declaration block:
selector {
property: value;
property: value;
/* More declarations */
}
Selectors
Selectors determine which HTML elements will be styled by the rule:
/* Element selector */
p {
color: blue;
}
/* Class selector */
.highlight {
background-color: yellow;
}
/* ID selector */
#header {
font-size: 24px;
}
/* Descendant selector */
article p {
line-height: 1.5;
}
/* Pseudo-class selector */
a:hover {
text-decoration: underline;
}
/* Attribute selector */
input[type="text"] {
border: 1px solid gray;
}
Properties and Values
Properties are specific aspects of an element's appearance, and values define how those properties should be displayed:
p {
color: #333; /* Text color */
font-family: Arial; /* Font */
font-size: 16px; /* Font size */
line-height: 1.5; /* Line height */
margin: 10px 0; /* Margin (top/bottom, left/right) */
padding: 5px; /* Padding on all sides */
text-align: justify; /* Text alignment */
border: 1px solid #ccc; /* Border */
}
How CSS Works
The Cascade
The cascade determines which styles are applied when multiple rules target the same element. It's based on:
- Importance: Styles marked with
!important
override other styles - Specificity: More specific selectors override less specific ones
- Source Order: Later styles override earlier ones
Specificity Hierarchy
Specificity is calculated as a four-part value: (Inline, IDs, Classes, Elements)
/* Specificity: 0,0,0,1 */
p {
color: black;
}
/* Specificity: 0,0,1,1 */
.content p {
color: blue;
}
/* Specificity: 0,1,0,1 */
#sidebar p {
color: red;
}
/* Specificity: 1,0,0,0 */
<p style="color: green;">This text is green</p>
Inheritance
Some CSS properties are inherited by an element from its parent element:
body {
font-family: Arial, sans-serif; /* Inherited by all descendants */
color: #333; /* Inherited by all descendants */
}
/* No need to set font-family for paragraphs since they inherit from body */
p {
margin: 1em 0; /* Not inherited */
}
CSS Box Model
The CSS box model describes the rectangular boxes generated for elements in the document tree:
┌────────────────────────┐
│ Margin │
│ ┌──────────────────┐ │
│ │ Border │ │
│ │ ┌──────────────┐ │ │
│ │ │ Padding │ │ │
│ │ │ ┌──────────┐ │ │ │
│ │ │ │ Content │ │ │ │
│ │ │ └──────────┘ │ │ │
│ │ └──────────────┘ │ │
│ └──────────────────┘ │
└────────────────────────┘
div {
width: 300px; /* Content width */
height: 200px; /* Content height */
padding: 20px; /* Space inside the border */
border: 5px solid #333; /* Border around the padding */
margin: 30px; /* Space outside the border */
}
Box-Sizing Property
The default box-sizing: content-box
can be counterintuitive since padding and border increase the total element size. Many developers prefer box-sizing: border-box
:
* {
box-sizing: border-box; /* Width includes padding and border */
}
CSS Layout
Display Property
The display
property determines how an element is treated in the layout flow:
/* Block elements (take full width, start on new line) */
div {
display: block;
}
/* Inline elements (take only necessary width, don't start new line) */
span {
display: inline;
}
/* Inline-block (inline but can have width/height) */
button {
display: inline-block;
}
/* Grid container */
.container {
display: grid;
}
/* Flexbox container */
.container {
display: flex;
}
/* Hide element */
.hidden {
display: none;
}
Position Property
The position
property determines how an element is positioned in the document:
/* Default - follows normal document flow */
.normal {
position: static;
}
/* Relative to its normal position */
.relative {
position: relative;
top: 10px;
left: 20px;
}
/* Positioned relative to the nearest positioned ancestor */
.absolute {
position: absolute;
top: 0;
right: 0;
}
/* Positioned relative to the viewport */
.fixed {
position: fixed;
bottom: 20px;
right: 20px;
}
/* Like fixed, but becomes relative when ancestor has a transform property */
.sticky {
position: sticky;
top: 0;
}
Flexbox Layout
Flexbox is designed for one-dimensional layouts (rows or columns):
.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 */
gap: 20px; /* gap between items */
}
.item {
flex: 1; /* flex-grow, flex-shrink, flex-basis combined */
align-self: flex-start; /* override alignment for specific item */
order: 2; /* change order of specific item */
}
Grid Layout
CSS Grid is designed for two-dimensional layouts (rows and columns):
.container {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* three columns with proportional widths */
grid-template-rows: auto 200px auto; /* three rows */
gap: 20px; /* gap between grid cells */
grid-template-areas: /* named grid areas */
"header header header"
"sidebar content content"
"footer footer footer";
}
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.content { grid-area: content; }
.footer { grid-area: footer; }
Responsive Web Design with CSS
Media Queries
Media queries allow styles to be applied conditionally based on device characteristics:
/* Base styles for all screen sizes */
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 {
.no-print {
display: none;
}
}
Responsive Units
/* Relative to font-size of the element */
.box {
padding: 1.5em;
}
/* Relative to font-size of the root element */
h1 {
font-size: 2rem;
}
/* Relative to viewport width */
.hero {
width: 80vw;
}
/* Relative to viewport height */
.full-height {
height: 100vh;
}
/* Responsive image */
img {
max-width: 100%;
height: auto;
}
CSS Selectors
Basic Selectors
/* Universal selector */
* {
box-sizing: border-box;
}
/* Type selector */
p {
margin-bottom: 1em;
}
/* Class selector */
.highlight {
background-color: yellow;
}
/* ID selector */
#header {
position: sticky;
top: 0;
}
/* Attribute selector */
input[type="checkbox"] {
margin-right: 0.5em;
}
Combinators
/* Descendant selector (any descendant) */
article p {
font-size: 0.9em;
}
/* Child selector (direct child only) */
ul > li {
list-style-type: square;
}
/* Adjacent sibling selector (immediately following) */
h2 + p {
font-weight: bold;
}
/* General sibling selector (any following sibling) */
h2 ~ p {
color: #666;
}
Pseudo-classes
/* Link states */
a:link { color: blue; }
a:visited { color: purple; }
a:hover { text-decoration: underline; }
a:active { color: red; }
/* Structural pseudo-classes */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
li:nth-child(odd) { background-color: #f9f9f9; }
li:nth-child(3n) { color: red; }
/* Form states */
input:focus { border-color: blue; }
input:disabled { background-color: #eee; }
input:checked + label { font-weight: bold; }
/* Content states */
div:empty { display: none; }
Pseudo-elements
/* First line and first letter */
p::first-line { font-variant: small-caps; }
p::first-letter { font-size: 2em; float: left; }
/* Before and after elements */
.quote::before { content: '"'; }
.quote::after { content: '"'; }
/* Selection style */
::selection { background: yellow; color: black; }
CSS Preprocessors
CSS preprocessors extend CSS with programming features:
Sass/SCSS Example
// Variables
$primary-color: #3498db;
$padding: 15px;
// Nesting
nav {
background: #333;
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
display: inline-block;
a {
color: white;
padding: $padding;
&:hover {
background: $primary-color;
}
}
}
}
// Mixins
@mixin border-radius($radius) {
-webkit-border-radius: $radius;
-moz-border-radius: $radius;
border-radius: $radius;
}
.button {
@include border-radius(5px);
}
// Extend/Inheritance
.message {
border: 1px solid #ccc;
padding: 10px;
color: #333;
}
.success {
@extend .message;
border-color: green;
}
.error {
@extend .message;
border-color: red;
}
CSS Frameworks
CSS frameworks provide pre-written CSS code for common design elements:
Popular Frameworks
- Bootstrap: Comprehensive framework with grid system, components, and utilities
- Tailwind CSS: Utility-first framework with composable classes
- Bulma: Modern CSS framework based on Flexbox
- Foundation: Advanced responsive front-end framework
CSS Animations and Transitions
Transitions
Transitions allow property changes to occur smoothly over time:
.button {
background-color: blue;
color: white;
padding: 10px 20px;
transition: background-color 0.3s ease, transform 0.2s ease;
}
.button:hover {
background-color: darkblue;
transform: scale(1.05);
}
Animations
Animations provide more control over animated sequences with keyframes:
@keyframes bounce {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-20px);
}
100% {
transform: translateY(0);
}
}
.bouncing-element {
animation: bounce 1s infinite ease-in-out;
}
/* Animation properties */
.custom-animation {
animation-name: slideIn;
animation-duration: 1s;
animation-timing-function: ease-out;
animation-delay: 0.5s;
animation-iteration-count: 3;
animation-direction: alternate;
animation-fill-mode: forwards;
/* Shorthand */
/* animation: slideIn 1s ease-out 0.5s 3 alternate forwards; */
}
CSS Variables (Custom Properties)
CSS variables allow values to be stored and reused throughout a document:
:root {
--primary-color: #3498db;
--secondary-color: #2ecc71;
--font-size-base: 16px;
--spacing-unit: 8px;
}
.header {
background-color: var(--primary-color);
padding: calc(var(--spacing-unit) * 2);
}
.button {
background-color: var(--secondary-color);
font-size: var(--font-size-base);
margin: var(--spacing-unit);
}
/* Scope variables to specific components */
.dark-theme {
--primary-color: #2980b9;
--text-color: white;
}
CSS Architecture and Methodologies
BEM (Block, Element, Modifier)
/* Block */
.card {
background: white;
border-radius: 4px;
}
/* Element */
.card__title {
font-size: 1.5em;
margin-bottom: 10px;
}
.card__image {
width: 100%;
}
/* Modifier */
.card--featured {
box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}
.card__title--large {
font-size: 2em;
}
OOCSS (Object-Oriented CSS)
/* Structure */
.media {
display: flex;
align-items: flex-start;
}
.media__image {
margin-right: 1em;
}
.media__content {
flex: 1;
}
/* Skin */
.theme-light {
background-color: white;
color: #333;
}
.theme-dark {
background-color: #333;
color: white;
}
CSS Best Practices
Organization
- Group related properties
- Use consistent naming conventions
- Comment your CSS, especially for complex selectors
- Use a logical file structure for larger projects
Performance
- Avoid overly specific selectors
- Minimize use of
!important
- Reduce redundancy with DRY (Don't Repeat Yourself) principles
- Use shorthand properties where appropriate
- Consider loading critical CSS inline
Maintainability
- Use a preprocessor for larger projects
- Create a style guide or component library
- Follow a CSS methodology (BEM, OOCSS, SMACSS, etc.)
- Use CSS variables for values that appear frequently
Modern CSS Features
Logical Properties
/* Traditional directional properties */
.box {
margin-left: 10px;
margin-right: 20px;
}
/* Logical properties (better for RTL support) */
.box {
margin-inline-start: 10px;
margin-inline-end: 20px;
}
Container Queries
.card {
display: flex;
flex-direction: column;
}
@container (min-width: 400px) {
.card {
flex-direction: row;
}
}
.container {
container-type: inline-size;
}
Subgrid
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: auto auto;
gap: 20px;
}
.item {
display: grid;
grid-template-columns: subgrid;
grid-column: span 3;
grid-template-rows: subgrid;
grid-row: span 2;
}
CSS Houdini
CSS Houdini is a set of APIs that give developers direct access to the CSS Object Model:
if ('paintWorklet' in CSS) {
CSS.paintWorklet.addModule('my-paint-worklet.js');
}
.element {
background-image: paint(myCustomPaint);
}
Conclusion
CSS is a powerful language that transforms the visual presentation of web pages. From basic styling to complex layouts and animations, CSS enables web developers to create beautiful, responsive, and accessible user interfaces. As the web continues to evolve, CSS grows with it, introducing new features and capabilities that make web design both more powerful and more intuitive.
By mastering CSS, front-end developers gain the ability to implement any design with precision, ensuring websites not only look good but also provide optimal user experiences across all devices and platforms. While learning the basics of CSS is relatively straightforward, truly mastering CSS involves understanding its nuances, keeping up with evolving specifications, and developing an eye for design implementation.