CSS Selectors For Beginners

CSS Selectors For Beginners

·

2 min read

You can't imagine a web page without styles (CSS). They play a key role in page beautification. The key to understanding the CSS is understanding the Selectors. Selectors are the patterns used to select specific HTML elements and apply styles.

Here I explain a few CSS selectors.

div

Matches div elements

<div>

#hashnode

Matches the id

<div id="hashnode">

h2 { }

Tag selector

<h2>Hi, Team</h2>

p .button

Matches any button that is a child of p

/* CSS */
p .button {
  background-color: green;
}

<!-- HTML -->
<p>
 <button class="button">Button</button>
</p>

.button

Matches the class button

<a class='button' />

div.button

Matches divs with the class "button"

<div class="button">

div > .background

Matches any background class that's a direct child of a div

/* CSS */
div > .background {
  background-color: yellow;
}

<!-- HTML -->
<div>
  <h2>My name is Srinivas</h2>
  <p class="background">I live in Hyderabad.</p>
</div>

a:hover

Matches the element the cursor is hovering over

ui li:first-child

Matches the first item of a list. Similarly we have last-item too

/* CSS */
ul li:first-child {
  background: #00ff00;
}

<!-- HTML -->
<ul>
 <li>First List</li>
 <li>Second List</li>
 <li>Third List</li>
 <li>Fourth List</li>
</ul>

a[href^="http"]

Matches links where the href attribute starts with "http"

:checked

Matches if a checkbox or radio button is checked

[data-model="open"] { }

Attribute selector

<div data-modal="open"></div>

:nth-child(2) { }

Positional selector

<ul>
  <li>nope</li>
  <!-- WILL match -->
  <li>yep, I'm #2</li>
  <li>nope</li>
</ul>

div:not(#header)

Matches all the divs expect the one with the id header

:empty { }

Pseudo selector

<!-- WILL match -->
<div></div>

<!-- WILL match -->
<aside data-blah><!-- nothin' --></aside>

<!-- Will NOT match -->
<div> </div>

<!-- Will NOT match -->
<div>
</div>

Selector combinations

.module > h2 {
  /* Select h2 elements that are direct children of an element with that class */
} 
h2 + p {
  /* Select p elements that are directly following an h2 element */
}
li ~ li {
  /* Select li elements that are siblings (and following) another li element. */
}

Hope it helps !