Last modified: December 29, 2022
This article is written in: 🇺🇸
CSS preprocessors and frameworks are two important tools in a web developer's toolbox that can help streamline the process of building websites. CSS preprocessors allow developers to use new functionality that is typically borrowed from another programming language, while frameworks provide pre-written app skeletons and collections of built-in functionality that allow developers to avoid having to write all of the code from scratch.
CSS preprocessors are scripting languages that extend standard CSS features with new functionality borrowed from other programming languages. Variables, nesting, inheritance, mixins, functions, and mathematical operations are common examples. While preprocessors don't introduce anything that can't be accomplished with plain CSS, they offer a more efficient way of doing things.
The two most common preprocessors are:
Let's delve into some of the most prevalent CSS preprocessor features and see how they stack up against CSS4, the latest iteration of CSS.
Variables facilitate the use of named values in different sections of the code. For instance, if you've utilized 'red' in various properties and later opt for 'blue', with a variable, you can alter the value in a singular location, as opposed to tracking down each instance individually.
CSS:
:root {
--important-color: red;
}
body {
color: var(--important-color);
}
SCSS:
$important-color: red;
body {
color: $important-color;
}
LESS:
@important-color: red;
body {
color: @important-color;
}
Inheritance copies all definitions from one selector to another.
CSS (Using @apply):
.parent {
color: red;
}
.child {
@apply .parent;
}
SCSS:
%parent {
color: red;
}
child {
@extend %parent;
}
LESS:
.parent {
color: red;
}
child {
.parent();
}
Nesting provides a more structured and readable way to write styles for nested elements. While CSS lacks a direct equivalent, the same effect can be achieved using multiple nested selectors.
SASS / LESS:
.parent {
.child {
color: red;
}
}
Mathematical operations enable dynamic value assignment based on another value, computed in real-time.
CSS:
body {
font-size: calc(100% - 10px);
}
SCSS / LESS:
body {
font-size: calc(100% - 10px);
}
Functions are named sets of instructions that take arguments and return a computed value. They provide a way to perform complex calculations or transformations on CSS properties.
CSS:
Available functions include:
rgb()
min()
max()
body {
background-color: rgb(255, 255, 255);
background-color: min(rgb(255, 255, 255), rgb(0, 0, 0));
background-color: max(rgb(255, 255, 255), rgb(0, 0, 0));
}
SCSS / LESS:
Available functions include:
lighten()
darken()
saturate()
body {
background-color: lighten(rgb(255, 255, 255), 10%);
background-color: darken(rgb(255, 255, 255), 10%);
background-color: saturate(rgb(255, 255, 255), 10%);
}
Mixins are reusable blocks of code that can be included in multiple CSS rules. They allow for writing DRY (Don't Repeat Yourself) code, avoiding repetition.
CSS (Using @apply, somewhat limited):
@custom-media --small-viewport (max-width: 30em);
@media (--small-viewport) {
/* Rules here */
}
SCSS:
@mixin small-viewport {
@media (max-width: 30em) {
@content;
}
}
@include small-viewport {
/* Rules here */
}
LESS:
.small-viewport(@rules) {
@media (max-width: 30em) {
@rules();
}
}
.small-viewport({
/* Rules here */
});
Conditionals and loops are not available in standard CSS. They allow for more dynamic and programmable stylesheets in preprocessors.
SCSS (Using conditionals and loops):
@for $i from 1 through 3 {
.item-#{$i} { width: 100px * $i; }
}
@if $theme == 'dark' {
body { background: black; }
} @else {
body { background: white; }
}
LESS (Similar capabilities):
.loop(@counter) when (@counter > 0) {
.item-@{counter} { width: 100px * @counter; }
.loop(@counter - 1);
}
.loop(3);
@theme: dark;
.body(@theme) when (@theme = dark) {
background: black;
},
.body(@theme) when (@theme = light) {
background: white;
}
.body(@theme);
Creating a "Hello World" project in Less (a CSS pre-processor) and compiling it to normal CSS involves a few steps. Here's a step-by-step guide in notes form:
I. Install Node.js and npm
II. Install Less
npm install -g less
.III. Create Your Project Directory
mkdir hello-world-less
.cd hello-world-less
.IV. Create a Less File
style.less
.style.less
in a text editor.
@color: green;
body {
color: @color;
}
V. Compile Less to CSS
lessc style.less style.css
.style.css
file with the compiled CSS.VI. Create an HTML File
index.html
.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
VII. View Your Project: Open index.html
in a web browser to view your project.
VIII. Deploy Your Project: For deployment, upload the index.html
and style.css
files to your web server or hosting provider.
Creating a "Hello World" project in SCSS (a CSS pre-processor) and compiling it to normal CSS involves a few steps. Here's a step-by-step guide in notes form:
I. Install Node.js and npm
II. Install Sass
npm install -g sass
.III. Create Your Project Directory
mkdir hello-world-scss
.cd hello-world-scss
.IV. Create a SCSS File
style.scss
.style.scss
in a text editor.
$color: green;
body {
color: $color;
}
V. Compile SCSS to CSS
sass style.scss style.css
.style.css
file with the compiled CSS.VI. Create an HTML File
index.html
.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
VII. View Your Project: Open index.html
in a web browser to view your project.
VIII. Deploy Your Project: For deployment, upload the index.html
and style.css
files to your web server or hosting provider.
CSS frameworks are essential tools in modern web development. They offer pre-written CSS code, helping developers to quickly build attractive and responsive websites without starting from scratch.
A CSS framework is a library meant to simplify and standardize the process of styling web pages. It typically includes:
Different frameworks cater to different needs:
CSS frameworks simplify web development by offering pre-styled components and layout systems that make it easier to build visually appealing, responsive websites. They share several foundational elements that ensure consistency, responsiveness, and ease of use. Understanding these common elements can help you leverage a framework effectively—or decide to create your own custom solution if you’d prefer.
To create a website that adapts well to different devices, it’s essential to consider how your content will display on mobile phones, tablets, and desktops. The viewport meta tag is a key tool for this, as it instructs browsers to scale your website based on the device’s width, making it look good on screens both large and small. By including <meta name="viewport" content="width=device-width, initial-scale=1" />
within the <head>
section of your HTML document, you’re ensuring that mobile users won’t need to zoom or scroll horizontally to view your content.
Every browser has default styling for HTML elements, which can lead to inconsistencies in how your website appears across different platforms. Developers use either CSS resets or normalization to create a consistent look. CSS resets, like Eric Meyer’s Reset CSS, remove all default browser styles, providing a blank canvas to work from. In contrast, Normalize.css maintains some sensible defaults, but it makes these consistent across browsers, reducing discrepancies. These approaches give you control over your design from the start, which is why they’re commonly included in CSS frameworks.
To make sure that padding and borders don’t unexpectedly affect the dimensions of your elements, you can set box-sizing: border-box
. This approach tells the browser to include padding and borders within an element’s specified width and height, which makes layouts more predictable. Frameworks often set this property globally, ensuring that all elements behave consistently, regardless of their styling.
Grids are a staple in CSS frameworks, providing a flexible way to create layouts that adapt to various screen sizes. Imagine dividing a page into columns that adjust based on screen size: on a desktop, you might have three columns side by side, while on a mobile screen, these columns would stack vertically to ensure readability. CSS frameworks often include predefined classes for these grid systems, allowing you to create responsive layouts without writing custom CSS. For example, you could assign a class to each “column” div and set it to span a specific fraction of the page. With media queries, you can then define how these columns behave on different screen sizes, ensuring your design remains user-friendly no matter the device.
Designing with a mobile-first mentality means starting with styles for the smallest screen sizes and progressively adding styles for larger screens. This approach is especially helpful because it prioritizes essential content and functionality for mobile users, who make up a significant portion of web traffic. You would begin by defining styles for mobile devices in your base CSS, then use media queries to adjust for tablets, laptops, and desktops. This method not only keeps your design responsive but also encourages you to focus on the most important elements of your site first.
Effective navigation is crucial to a positive user experience on any website. CSS frameworks often include pre-styled navigation components, such as horizontal menus for desktops and collapsible hamburger menus for mobile. This makes it easier to implement a cohesive navigation experience without starting from scratch. To keep navigation accessible, make sure that it’s clearly structured and easy to interact with on both desktop and mobile devices. For example, a navigation bar with large clickable areas is more accessible to users with motor disabilities and also provides a more comfortable experience for users on touch devices.
Typography affects both the readability and overall aesthetic of your site. CSS frameworks typically include a set of font styles, sizes, and line heights for headings, paragraphs, and lists, ensuring a harmonious hierarchy throughout your content. Good typography helps users consume information with ease and encourages them to stay on your site longer. Some frameworks also include responsive typography settings, where font sizes adjust based on screen width. This way, headings and body text remain readable and proportional, regardless of the device.
A well-designed color scheme can make your website feel cohesive and professional. Many frameworks offer predefined color palettes, saving you time by providing a set of harmonized colors that can be applied across your site. In some frameworks, you can even customize themes to fit your brand’s color scheme. For instance, you might define your brand’s primary color in a variable and apply it to buttons, links, and other key elements. This approach makes it easy to maintain consistency throughout your site and creates a distinct visual identity.
Utility classes are small, single-purpose CSS classes that can be applied directly in HTML to style elements quickly. For example, a utility class like .text-center
might center-align text, while .m-4
could add a medium margin around an element. These classes speed up development by allowing you to add spacing, alignment, or other styles without writing custom CSS. While utility classes can make styling faster, it’s wise to balance their use to keep your HTML clean and maintainable.
Forms are one of the most common interactive elements on websites, so it’s essential that they’re user-friendly. CSS frameworks include consistent styling for inputs, buttons, checkboxes, and other form elements, ensuring they look cohesive across devices. Many frameworks also incorporate styles for validation states, such as red outlines for invalid fields, which improves the overall usability of forms. Additionally, frameworks often prioritize accessibility by including styles that make form elements easier to interact with for screen reader users or those with mobility impairments.
Grid systems are at the core of responsive web design, allowing for complex layouts that scale seamlessly across different screen sizes. CSS frameworks usually include a grid system that enables you to define rows and columns to create the structure of your page. Each column can be set to span a specific fraction of the row, and by using media queries, the framework will automatically adjust these columns for different screen widths. This flexibility helps ensure that your content remains well-organized and aesthetically pleasing on both small and large screens.
CSS frameworks are designed to streamline the web development process by providing these tools and components, which all contribute to a responsive, cohesive, and visually appealing website. Understanding and effectively using these elements can greatly enhance your productivity as a developer and improve the user experience for those visiting your site.
Bootstrap is a widely-used, open-source front-end framework for designing responsive websites and web applications. Initially developed by Twitter engineers Mark Otto and Jacob Thornton in 2011, it leverages HTML, CSS, and JavaScript to facilitate the creation of mobile-first and responsive designs.
To use Bootstrap, add the following link to the <head>
section of your HTML file:
<link crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" rel="stylesheet"/>
With this, Bootstrap's default styles will be applied to elements like <body>
, <h1>
, <button>
, etc. For additional styling, use the appropriate Bootstrap class attributes in your HTML.
Containers are a fundamental concept in Bootstrap. They are used to encapsulate page content and provide consistent padding and centering.
I. Fixed-Width Container (container
): This class is used for a responsive fixed-width container. The width changes at different breakpoints (screen sizes), but it's always centered and padded from the viewport edges.
<div class="container">
<h1>Hello World</h1>
<!-- Your content here -->
</div>
II. Full-Width Container (container-fluid
): This class creates a container that spans the entire width of the viewport. Useful for layouts that need to fill the whole width of the screen.
<div class="container-fluid">
<h1>Full Width Content</h1>
<!-- Your content here -->
</div>
Bootstrap’s grid system allows you to create complex layouts using a series of rows and columns.
How the Grid System Works:
row
): A row is a horizontal grouping of columns. It ensures that columns within it are aligned properly and have equal heights.col-*
): Columns are the vertical divisions of the grid. Bootstrap's grid system allows for up to 12 columns across the page.Example of a 3-Column Layout:
<div class="container">
<div class="row">
<div class="col-md-4">Column 1 Content</div>
<div class="col-md-4">Column 2 Content</div>
<div class="col-md-4">Column 3 Content</div>
</div>
</div>
In this example, each col-md-4 class signifies that each column takes up 4 out of the 12 possible columns in the grid on medium-sized devices and larger.
Bootstrap's components and grid system are designed to be responsive, adapting to various screen sizes.
Example of Responsive Columns:
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-6">Content</div>
<div class="col-md-4 col-sm-6">Content</div>
<div class="col-md-4 col-sm-12">Content</div>
</div>
</div>
In this example:
Bootstrap provides several components for creating navigation bars and menus, which are essential for user navigation in websites.
The Navbar component is a responsive and versatile horizontal bar that can contain a brand, navigation links, forms, and other content.
Example of a Basic Navbar:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Navbar</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
</ul>
</div>
</nav>
Breadcrumb navigation is a simple navigation aid that helps users understand their current location within a website and navigate back to parent pages.
Example of a Breadcrumb:
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item"><a href="#">Library</a></li>
<li aria-current="page" class="breadcrumb-item active">Data</li>
</ol>
</nav>
Example of Different Button Styles:
<button class="btn btn-primary" type="button">Primary</button>
<button class="btn btn-secondary" type="button">Secondary</button>
<!-- Additional button styles as needed -->
Example of a Simple Form:
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input aria-describedby="emailHelp" class="form-control" id="exampleInputEmail1" type="email"/>
<small class="form-text text-muted" id="emailHelp">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input class="form-control" id="exampleInputPassword1" type="password"/>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
Example of an Alert:
<div class="alert alert-warning" role="alert">
This is a warning alert—check it out!
</div>
Bootstrap offers a wide range of typography classes to style your text content effectively.
<h1>
to <h6>
..lead
class to make a paragraph stand out.<small>
tag or .small
class for de-emphasized text.Example of Typography Classes:
<h1 class="display-1">Display Heading 1</h1>
<h2>Regular Heading 2</h2>
<p class="lead">This is a leading paragraph.
Regular paragraph text.
<small class="text-muted">This is a small, muted text.</small>
Bootstrap’s customization ability lets you tailor the framework to fit your design needs.
Customizing with SASS/SCSS:
Build Tools for Customization:
Example of Customizing Bootstrap with SCSS:
// Customizing the primary color
$theme-colors: (
"primary": #ff6347 // Tomato color
);
@import "bootstrap";
In this SCSS example, the $theme-colors map is overridden to change the primary color used throughout Bootstrap components.
Creating a basic "Hello World" project with Bootstrap involves the following steps. This guide assumes you are familiar with basic HTML and CSS:
I. Set Up Your HTML File
index.html
.index.html
in a text editor.II. Include Bootstrap
<head>
tag, include Bootstrap’s CSS:
<link crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ775iR6n9rC6jxo2E5h7X/0pZ72n/VAapMo" rel="stylesheet"/>
</body>
tag, include Bootstrap’s JS and its dependencies:
<script crossorigin="anonymous" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
III. Create a Basic Layout
<div class="container">
<h1>Hello World</h1>
</div>
IV. Customize with Bootstrap Classes: Utilize Bootstrap's classes for typography, buttons, or other components to enhance your page.
V. View Your Project: Open index.html
in a web browser to view your Bootstrap-styled "Hello World" project.
You’re absolutely right! Let’s present this information in the correct format as specified.
@import
directive in Sass or Less to create a modular structure, making the codebase more maintainable and readable.Here are some helpful resources for working with Bootstrap, understanding CSS frameworks, and improving your web development skills: