css selectors

How to use CSS selectors

To apply CSS to an element we need to select it. It is used to select the content you want to style

What is CSS selectors?

          CSS selectors define the elements to which a specific set of rules apply. It is the first part of CSS rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.

Syntax:

Selector{

          propertyName: value;

          propertyName: value;

          }

Types of Selectors:

  • Element
  • ID
  • Universal
  • Class
  • Attribute

Element Selector:

This selects HTML elements based on the element tag name like <p>, <h1> etc.,

p {
  text-align: center;
  color: red;
}

Universal selector

Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces.
Syntax: * ns|* *|*
Example: * will match all the elements of the document.

* {
  text-align: center;
  color: blue;
}

Type selector

Selects all elements that have the given node name.
Syntax: elementname
Example: input will match any <input> element.

Class selector

Selects all elements that have the given class attribute.
Syntax: .classname
Example: .index will match any element that has a class of “index”.

.index {
  text-align: center;
  color: red;
}

To specify only specific HTML elements of a class to be affected

p.index {
  text-align: center;
  color: red;
}

Here only elements with tag <p> are affected in class index.

ID selector

Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document.
Syntax: #idname
Example: #p1 will match the element that has the ID “p1”.

#p1 {
  text-align: center;
  color: red;
}

Attribute selector

Selects all elements that have the given attribute.
Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
Example: [autoplay] will match all elements that have the autoplay attribute set (to any value).

a[target] {
  background-color: yellow;
}

CSS Grouping Selector

Grouping Selector selects all HTML elements with same style definitions.

To group selectors , we separate with comma ,

h1, h2, p {
  text-align: center;
  color: red;
}