Selectors in CSS -Part 1

In this article we will learn some basic methodology of selectors

Why we use selectors?

The main use case of selectors is to gain control over the HTML layout,through selectors we can target any HTML element either individually or by grouping or by some internal relation between elements within HTML file and we can style them as we like.

Exploring Selectors in CSS:

To begin with lets start with,

Element Selector:

Element selector targets HTML elements by their tag name.

For example ,

<body>
<p>Hello ,Everyone</p>
</body>

We can target above p tag using element selector.

p{
background-color:blue;
}

ID Selector:

ID Selector targets HTML elements by using the unique id attribute.

<body>
<p id="display">Displaying content</p>
</body>

we can target above p tag using the value given to id attribute.

#display{
background-color:red;
}

Class selector:

Class selector targets HTML element by using class attribute.

<body>
<p class="select">Content of selected p tag</p>
</body>

We can target above p tag using the value given to the class attribute.

.select{
color:gold;
}

Universal Selector:

Universal Selector selects all the elements in the page.

*{
//property:value;  
//styleing to be applied to all elements
}

Descendant Selector:

Descendant Selector targets the HTML elements that are descendants of parent element.

<div class="container">
<h1>Header 1</h1>
<p>Paragraph inside container</p>
</div>

We can select the above p tag using descendant selector in the following way.

.container p{
color:yellow;
}

Child Selector:

Child Selector targets HTML elements that are direct children to specified parent element.

<div class="container">
<h1>Heading 1</h1>
<p>Paragraph inside container</p>
<div>
<p>Nested paragraph </p>
</div>
</div>

We can select the above p tag which is direct child of div having container as value to the class as below

.container>p{
background-color:blue;
}

Adjacent Sibling Selector:

Adjacent Sibling Selector targets HTML element that immediately preceded by another specified element.

<div>
<h2>Heading 2</h2>
<p>first Paragraph</p>
<p>second Paragraph</p>
</div>

We can select the first p tag as follows,

h2+p{
background-color:black;
}

Sibling Selector:

Sibling Selector targets HTML elements that are siblings to the specified element irrespective of how they appear after or before of sibling element.

<div>
<h2>Heading 2</h2>
<p>first Paragraph</p>
<p>second Paragraph</p>
<p>third Paragraph</p>
</div>

We can select all the paragraphs inside div as below,

h2~p{
background-color:green;
}