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.
What is CSS?
- CSS stands for Cascading Style Sheets
- CSS describes how HTML elements are to be displayed
- CSS saves a lot of work by controlling the layout of multiple web pages all at once
- External stylesheets are stored in CSS files
CSS was created by HÃ¥kon Wium Lie and Bert Bos. The first version of CSS was released in 1996. Since then, there have been several versions of CSS, with CSS3 being the latest major version (though CSS is now developed in modules).
Why Use CSS?
CSS is used to define styles for your web pages, including the design, layout, and variations in display for different devices and screen sizes. Here are some key benefits of using CSS:
- Separation of content and presentation - HTML provides the structure, CSS provides the style
- Consistency - Apply the same styles to multiple elements across multiple pages
- Efficiency - Change the appearance of an entire website by modifying a single file
- Responsive design - Adapt your website's appearance for different devices and screen sizes
- Enhanced user experience - Create visually appealing and user-friendly interfaces
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.
CSS Rule Syntax
selector {
property: value;
property: value;
property: value;
}
Each declaration includes a CSS property name and a value, separated by a colon. A CSS declaration always ends with a semicolon, and declaration blocks are surrounded by curly braces.
p {
color: red;
text-align: center;
font-size: 16px;
}
This paragraph is styled with CSS.
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 */
Ways to Insert CSS
There are three ways to insert CSS into your HTML:
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 Best Practices
For maintainability and separation of concerns, it's generally recommended to:
- Use external CSS files whenever possible
- Use internal CSS when styles apply to a single page
- Use inline CSS sparingly, only when necessary for a specific element
CSS Selectors
CSS selectors are used to "find" (or 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.
/* Unvisited link */
a:link {
color: blue;
}
/* Visited link */
a:visited {
color: purple;
}
/* Mouse over link */
a:hover {
color: red;
}
/* Selected link */
a:active {
color: green;
}
Hover over this link to see the effect.
Pseudo-elements
A CSS pseudo-element is used to style specified parts of an element.
/* First line of a paragraph */
p::first-line {
font-weight: bold;
}
/* First letter of a paragraph */
p::first-letter {
font-size: 200%;
color: red;
}
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Attribute Selectors
Attribute selectors select elements based on an attribute or attribute value.
/* Selects all elements with a target attribute */
[target] {
background-color: yellow;
}
/* Selects all elements with target="_blank" */
[target="_blank"] {
background-color: red;
}
/* Selects all elements with an href attribute containing "example" */
[href*="example"] {
color: green;
}
/* Selects all elements with an href attribute starting with "https" */
[href^="https"] {
color: blue;
}
/* Selects all elements with an href attribute ending with ".pdf" */
[href$=".pdf"] {
color: red;
}
CSS Colors
Colors in CSS can be specified in several ways:
Color Names
CSS supports 140 standard color names.
h1 {
color: red;
}
p {
color: navy;
}
div {
color: orange;
}
This heading is red
This paragraph is navy
RGB and RGBA Colors
RGB (Red, Green, Blue) is a color model where colors are specified using red, green, and blue light values. RGBA adds an Alpha channel for transparency.
h1 {
color: rgb(255, 0, 0); /* Red */
}
p {
color: rgb(0, 0, 128); /* Navy */
}
div {
color: rgba(255, 165, 0, 0.5); /* Semi-transparent orange */
}
This heading is rgb(255, 0, 0)
This paragraph is rgb(0, 0, 128)
Hexadecimal Colors
Hexadecimal color values are specified with: #RRGGBB, where RR (red), GG (green), and BB (blue) are hexadecimal values between 00 and FF.
h1 {
color: #FF0000; /* Red */
}
p {
color: #000080; /* Navy */
}
div {
color: #FFA500; /* Orange */
}
This heading is #FF0000
This paragraph is #000080
HSL and HSLA Colors
HSL (Hue, Saturation, Lightness) is an alternative representation of the RGB color model. HSLA adds an Alpha channel for transparency.
h1 {
color: hsl(0, 100%, 50%); /* Red */
}
p {
color: hsl(240, 100%, 25%); /* Navy */
}
div {
color: hsla(39, 100%, 50%, 0.5); /* Semi-transparent orange */
}
This heading is hsl(0, 100%, 50%)
This paragraph is hsl(240, 100%, 25%)
Current Color
The currentColor
keyword represents the value of an element's color
property.
div {
color: blue;
border: 1px solid currentColor; /* Border will be blue */
}
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:
Text Styling
CSS provides various properties to style text content.
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 |
Shorthand property for setting all font properties | font: italic bold 16px/1.5 Arial, sans-serif; |
p.serif {
font-family: "Times New Roman", Times, serif;
}
p.sansserif {
font-family: Arial, Helvetica, sans-serif;
}
p.monospace {
font-family: "Courier New", Courier, monospace;
}
This is a paragraph in Times New Roman.
This is a paragraph in Arial.
This is a paragraph in Courier New.
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; |
line-height |
Sets the height of a line of text | line-height: 1.5; |
letter-spacing |
Increases or decreases the space between characters | letter-spacing: 2px; |
word-spacing |
Increases or decreases the space between words | word-spacing: 4px; |
p.uppercase {
text-transform: uppercase;
}
p.lowercase {
text-transform: lowercase;
}
p.capitalize {
text-transform: capitalize;
}
This is uppercase text.
This is LOWERCASE text.
this is capitalized text.
CSS Units
CSS has several different units for expressing length. Some are absolute, while others are relative.
Absolute Units
Absolute units are fixed and will appear as exactly that size.
Unit | Description |
---|---|
px |
Pixels (1px = 1/96th of 1in) |
pt |
Points (1pt = 1/72nd of 1in) |
pc |
Picas (1pc = 12pt) |
in |
Inches |
cm |
Centimeters |
mm |
Millimeters |
Relative Units
Relative units are relative to something else, such as the size of the parent element's font or the size of the viewport.
Unit | Description |
---|---|
em |
Relative to the font-size of the element (2em means 2 times the size of the current font) |
rem |
Relative to font-size of the root element |
vw |
Relative to 1% of the width of the viewport |
vh |
Relative to 1% of the height of the viewport |
% |
Relative to the parent element |
body {
font-size: 16px;
}
.parent {
font-size: 20px;
}
.px {
font-size: 24px; /* Always 24px */
}
.em {
font-size: 1.5em; /* 1.5 times the parent element's font size */
}
.rem {
font-size: 1.5rem; /* 1.5 times the root element's font size */
}
.percent {
font-size: 150%; /* 150% of the parent element's font size */
}
Practice Exercises
Now that you've learned the basics of CSS, it's time to practice! Here are some exercises to help you reinforce what you've learned.
Exercise 1: Style a Paragraph
Create a CSS rule to style a paragraph with the following properties:
- Font family: Arial, sans-serif
- Font size: 18px
- Color: #333333
- Line height: 1.5
- Text alignment: justified
Exercise 2: Create a Button
Create a CSS rule to style a button with the following properties:
- Background color: #4CAF50
- Text color: white
- Padding: 10px 20px
- Border: none
- Border radius: 4px
- Font size: 16px
- Add a hover effect that changes the background color to #45a049
Exercise 3: Style a Navigation Menu
Create CSS rules to style a horizontal navigation menu with the following properties:
- Remove the default list styling (bullets and margin)
- Display list items inline or use flexbox
- Add padding and margin to create space between menu items
- Style the links with a different color for normal, hover, and active states