1. CSS Basics

CSS Syntax and Selectors

1. CSS Syntax

CSS is written using rules. Each rule targets one or more HTML elements and applies a set of styles to them.

Basic Syntax

selector {
  property: value;
}

Example

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

In the above rule:

  • p is the selector. It targets all <p> elements.
  • color and font-size are properties.
  • blue and 16px are values.
  • A semicolon is used to separate each property-value pair.
  • Curly braces {} wrap all the declarations.

2. Types of Selectors

CSS provides different types of selectors to target HTML elements in various ways.

2.1. Universal Selector

Targets all elements in the document.

* {
  margin: 0;
  padding: 0;
}

2.2. Element Selector (Type Selector)

Targets all HTML elements of a specific type.

h1 {
  color: red;
}

2.3. Class Selector

Targets all elements with a specific class attribute. A dot . is used to define a class.

.myclass {
background-color: yellow;
}

Usage in HTML:

<div class="myclass">This is a div</div>

2.4. ID Selector

Targets a single element with a specific ID attribute. A hash # is used to define an ID.

#main {
  width: 100%;
}

Usage in HTML:

<div id="main">Main section</div>

2.5. Grouping Selector

Applies the same style to multiple selectors.

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

2.6. Descendant Selector

Targets elements inside other elements.

div p {
  color: green;
}

This targets all <p> elements that are inside a <div>.

2.7. Child Selector

Targets only direct children of an element.

ul > li {
  list-style-type: square;
}

This targets only <li> elements that are direct children of a <ul>.

2.8. Adjacent Sibling Selector

Targets an element that is immediately after another element.

h1 + p {
  margin-top: 10px;
}

This targets the first <p> that comes right after an <h1>.

2.9. General Sibling Selector

Targets all siblings of an element.

h1 ~ p {
  color: gray;
}

This targets all <p> elements that are siblings of an <h1>.

2.10. Attribute Selector

Targets elements with specific attributes.

input[type="text"] {
  border: 1px solid black;
}

This targets all <input> elements where type="text".

3. Class vs ID Summary

  • Use .class when you want to apply styles to multiple elements.
  • Use #id when you want to style a single unique element.

4. CSS Comments

You can write comments in CSS using this syntax:

/* This is a CSS comment */

Comments are ignored by the browser and used only for notes or explanations in the code.

Summary

  • CSS rules follow the syntax: selector { property: value; }
  • Selectors help you target HTML elements in different ways
  • Mastering selectors is essential for applying styles efficiently and building clean code

Scroll to Top