CSS Introduction
CSS (Cascading Style Sheets) is used to style and lay out web pages — for example, to alter the font, color, size, and spacing of your content.
How to Add CSS
There are three ways to insert CSS: external, internal, and inline styles. For most projects, using an external stylesheet is the best practice.
<!-- External CSS -->
<link rel="stylesheet" href="styles.css">
<!-- Internal CSS -->
<style>
body {
background-color: lightblue;
}
</style>
<!-- Inline CSS -->
<h1 style="color:blue;text-align:center;">This is a heading</h1>
Selectors
CSS selectors are used to "find" (or select) the HTML elements you want to style. We can divide selectors into five categories:
- Simple selectors (select elements based on name, id, class)
- Combinator selectors (select elements based on a specific relationship between them)
- Pseudo-class selectors (select elements based on a certain state)
- Pseudo-elements selectors (select and style a part of an element)
- Attribute selectors (select elements based on an attribute or attribute value)
/* Element Selector */
p {
color: red;
}
/* ID Selector */
#unique-element {
border: 1px solid black;
}
/* Class Selector */
.highlight {
background-color: yellow;
}
The 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.
div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
Flexbox
The Flexbox Layout module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.
Pro Tip: A Complete Guide to Flexbox
For a deep dive into all the properties and capabilities of Flexbox, check out the excellent guide on CSS-Tricks.
.container {
display: flex;
justify-content: space-around; /* Distributes items evenly */
align-items: center; /* Vertically aligns items */
height: 200px;
}