CSS

CSS – Selectors, Type with Examples

CSS Selectors

A CSS Selector is the part of the CSS ruleset that actually selects the content that you want to style.

As the name suggests, it selects and manipulates HTML documents (s).

So they are used to select and manipulate HTML documents on the basis of their id, class, type and attributes, and some more.

Universal Selector

The universal selector works like a wild card character. It will select all the elements of the page.

The universal selector is written  ” * ” matches the name of the element type.

If you define a universal selector then all elements will be affected by it. It is widely used to combine with another selector.

CSS Example
*{
margin:0;
padding:0;
}

  The above example will make all elements margin and padding ‘0’.

CSS Example
*{
       color:#f00;
       font-size:#0f0;
       background-color:#fff;
}

Here, color, font-size, and background-color are defined inside the universal selector. As you can see universal selector is declared with an asterisk ” * “.

Element selector

The element selector selects the HTML documents on the basis of their element name.

This selector must match one or more HTML elements of the same name. For instance, all the elements included inside the tag <p> can be modified. Below is an example:

CSS Example
p {
      text-align: center;
      color: red;
}
HTML Section
<p>Every paragraph will be affected by the style.</p>
<p id="para1">Me too!</p>
<p>And me!</p>

There is a three-paragraph <p> elements all are affected by the above style. Note that if there are more other elements then you have to pick them up to style.

ID Selector

The ID selector is declared using a hash [#] or a pound symbol preceding a string of characters.  

ID selector is a unique selector that is specially used to find the unique element. It uses the id attribute to find the specific element of an HTML tag.

CSS Example
#para1 {
    text-align: center;
    color: red;
}
HTML Section
<p id="para1">Hello World!</p>
<p>This paragraph is not affected by the style.</p>

The element is pointed by id #para1 while styling #para1 that won’t affect other paras.

Here #para1 is the string character that is defined by the developer to indicate the element easily.

Class Selectors

This is one of the most useful selectors in CSS. It is declared with the (. ) preceding the character.

This one finds the elements with the specific class and uses the HTML class attribute. To find the elements, we must write a period character followed by the name of the class.

CSS Example
.center {
             text-align: center;
             color: red;
}

The class selector is always declared with the ( . ) dot sign.

HTML Section
<h1 class="center">Red and center-aligned heading</h1>
<p class="center">Red and center-aligned paragraph.</p>
Back to top button