Css Selectors and Examples

Css Selectors and Examples

CSS selectors, also known as tags are used to target specific HTML elements and apply styling to them. Each CSS selectors targets a specific type of element or a group of elements on a webpage.

1. Element Selector

The element selector targets HTML elements by their tag names.

Syntax: element { property: value; }

Example:

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

2. Class Selector

The class selector targets elements with a specific class attribute.

Syntax: .class { property: value; }

Example:

.button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 20px;
  border: none;
  text-align: center;
  display: inline-block;
  font-size: 16px;
}

3. ID Selector

The ID selector targets a single element with a specific ID attribute.

Syntax: #id { property: value; }

Example:

#header {
  background-color: #333;
  color: white;
  padding: 20px;
  text-align: center;
}

4. Attribute Selector

The attribute selector targets elements with a specific attribute or attribute value.

Syntax: [attribute="value"] { property: value; }

Example:

input[type="text"] {
  width: 100%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}

5. Descendant Selector

The descendant selector targets elements that are descendants of a specified element.

Syntax: parent_element descendant_element { property: value; }

Example:

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

6. Child Selector

The child selector targets elements that are direct children of a specified parent element.

Syntax: parent_element > child_element { property: value; }

Example:

.menu > li {
  display: inline-block;
  margin-right: 20px;
}

7. Universal Selector

The universal selector targets all elements on a webpage.

Syntax: * { property: value; }

Example:

* {
  box-sizing: border-box;
}

Wrapping Up

These are some of the fundamental CSS selectors that you can use to style your HTML elements. By understanding how each selector works and practicing with examples, you’ll be able to apply styles effectively and create visually appealing webpages!

Leave a Reply

Your email address will not be published. Required fields are marked *