Skip to content

Latest commit

 

History

History
166 lines (127 loc) · 3.08 KB

selectors.md

File metadata and controls

166 lines (127 loc) · 3.08 KB

⚑ CSS Selectors

The CSS Selectors are used to target specific elements in an HTML document to assign value for their property to apply styles to them.

There are almost 9 type of selectors in CSS.

☴ Overview:

  1. Element Selectors
  2. Class Selectors
  3. ID Selectors
  4. Universal Selector
  5. Descendant Selectors
  6. Child Selectors
  7. Adjacent Sibling Selectors
  8. General Sibling Selectors
  9. Attribute Selectors

✦ Element Selectors:

It targets the elements based on their tag name.

Syntax: tag_name

p {
  color: blue;
}

✦ Class Selectors:

It targets elements based on a class attribute.

Syntax: .class_name

<div class="my-class">This is a div with some content</div>
.my-class {
  font-weight: bold;
}

✦ ID Selectors:

It targets a single element based on its unique ID attribute.

Syntax: #id_name

<h1 id="my-heading">This is a heading</h1>
#my-heading {
  text-align: center;
}

✦ Universal Selector:

It targets all elements in the HTML document.

Syntax: *

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

✦ Descendant Selectors:

It targets elements that are descendants of another element.

Syntax: parent_element child_element

div p {
  color: green;
}

✦ Child Selectors:

It targets elements that are direct children of another element.

Syntax: parent_element > child_element

div > p {
  color: green;
}

✦ Adjacent Sibling Selectors:

It targets the next element that is a sibling of the current element.

Syntax: element1 + element2

p + span {
  font-style: italic;
}

✦ General Sibling Selectors:

It targets all elements that are siblings of the current element.

Syntax: element1 ~ element2

h1 ~ p {
  color: red;
}

✦ Attribute Selectors:

It targets elements based on their attributes.

Syntax:

  • [attribute_name]
  • [attribute_name="value"]
  • [attribute_name^="value"] (starts with)
  • [attribute_name$="value"] (ends with)
  • [attribute_name*="value"] (contains)

Apply style to the a tag having the attribute name

a[href] {
  color: blue;
}

Apply style to the a tag with attribute value equals to aboutus.html

a[href="aboutus.html"] {
  color: blue;
}

Apply style to the a tag with attribute value starts with https://

a[href^="https://"] {
  color: blue;
}

Apply style to the a tag with attribute value ends with .html

a[href$=".html"] {
  color: blue;
}

Apply style to the a tag with attribute value contains products

a[href*="products"] {
  color: blue;
}

⇪ To Top

❮ Previous TopicNext Topic ❯

⌂ Goto Home Page