CSS Tutorial: First Steps


Introduction

CSS (Cascading Style Sheets) is used to style HTML elements, making web pages visually appealing. This tutorial will introduce you to the basics of CSS, including syntax, selectors, properties, and examples.


What is CSS?

CSS is a stylesheet language that describes how HTML elements should be displayed. It allows you to apply styles such as colors, fonts, layouts, and more.

How to Add CSS to HTML

There are three ways to apply CSS to an HTML document:

1. Inline CSS

Applied directly within an HTML element using the style attribute.

<p style="color: blue; font-size: 20px;">This is a styled paragraph.</p>

2. Internal CSS

Defined within a <style> tag inside the <head> section of an HTML document.

<head>
    <style>
        p {
            color: blue;
            font-size: 20px;
        }
    </style>
</head>

3. External CSS

Stored in a separate .css file and linked using the <link> tag.

<head>
    <link rel="stylesheet" href="styles.css">
</head>

Content of styles.css:

p {
    color: blue;
    font-size: 20px;
}

CSS Syntax

CSS follows a simple syntax:

selector {
    property: value;
}

Example:

h1 {
    color: red;
    font-size: 30px;
}

CSS Selectors

Selectors define which HTML elements should be styled.

1. Element Selector

Targets specific HTML elements.

h1 {
    color: green;
}

2. Class Selector

Targets elements with a specific class.

.my-class {
    color: purple;
}

HTML:

<p class="my-class">This is a styled paragraph.</p>

3. ID Selector

Targets an element with a unique ID.

#unique-id {
    background-color: yellow;
}

HTML:

<p id="unique-id">This paragraph has a background color.</p>

4. Grouping Selector

Applies styles to multiple elements at once.

h1, h2, p {
    font-family: Arial, sans-serif;
}

Common CSS Properties

1. Text Properties

p {
    color: blue;
    font-size: 18px;
    font-weight: bold;
    text-align: center;
}

2. Background and Borders

body {
    background-color: lightgray;
}

.box {
    border: 2px solid black;
    background-color: white;
    padding: 20px;
}

3. Margins and Padding

div {
    margin: 20px;
    padding: 10px;
}

4. Width and Height

div {
    width: 300px;
    height: 150px;
}

5. Display and Positioning

.box {
    display: inline-block;
    position: absolute;
    top: 50px;
    left: 100px;
}

Responsive Design

To make websites mobile-friendly, CSS provides features like media queries:

@media (max-width: 600px) {
    body {
        background-color: lightblue;
    }
}

This tutorial covered the basics of CSS, including syntax, selectors, and key properties. By combining CSS with HTML, you can create visually appealing web pages. Next, explore advanced topics like Flexbox, Grid, and animations!

You can also learn more about Web Programming here:

JavaScript

HTML


Happy coding!

Comments