CSS Tutorial: Getting Started with Styling Your Web Pages
CSS (Cascading Style Sheets) is a language used to describe how HTML elements should be displayed on the screen, paper, or in other media. It controls the layout of multiple web pages all at once and enhances the look and feel of websites.
Why Use CSS?
- Separation of content and design: HTML is used for structure, and CSS handles presentation, which makes managing a large site easier.
- Consistency: CSS allows the same styles to be applied to multiple pages, ensuring consistent design.
- Improved maintainability: Changes can be made to a single CSS file to update the entire site, rather than editing each HTML file.
Basic CSS Structure
A CSS rule consists of two parts: a selector and a declaration block.
- Selector: The HTML element you want to style.
- Property: The attribute you want to change, such as
color
or font-size
.
- Value: The value you want to assign to the property, such as
red
or 16px
.
Example 1: Inline, Internal, and External CSS
-
Inline CSS: Add styles directly within an HTML element. Example:
-
Internal CSS: Place CSS rules inside a <style>
tag in the head of the HTML document.
-
External CSS: Link an external CSS file to the HTML document using a <link>
tag.
HTML file:
styles.css
file:
Selectors in CSS
1. Element Selector
Targets HTML elements directly by name.
2. Class Selector
Used to select elements with a specific class. To select, use a dot (.
) followed by the class name.
HTML:
3. ID Selector
An ID is unique to each element and is selected using a hash symbol (#
).
HTML:
4. Universal Selector
The universal selector (*
) applies to all elements.
5. Group Selector
Use this to style multiple elements the same way.
Colors in CSS
You can set colors using:
- Name:
color: red;
- Hexadecimal:
color: #ff0000;
- RGB:
color: rgb(255, 0, 0);
- RGBA (with transparency):
color: rgba(255, 0, 0, 0.5);
Fonts in CSS
To style text, use font properties such as font-family
, font-size
, font-weight
, and font-style
.
Example 2: Styling Multiple Elements
Let’s create an example with a styled header, paragraph, and button.
HTML:
CSS (style.css
):
CSS Box Model
The box model consists of margins, borders, padding, and the content area. Every element in CSS is treated as a rectangular box.
- Margin: Space outside the border.
- Border: A line around the padding and content.
- Padding: Space between the border and the content.
- Width/Height: The size of the content area.
CSS Layouts: Flexbox and Grid
Flexbox Layout
Flexbox makes it easier to align items along a single axis (horizontal or vertical).
Grid Layout
CSS Grid is a two-dimensional layout system that allows items to be placed in rows and columns.
Media Queries for Responsive Design
Media queries are used to apply styles based on screen size or device type.