Everthing About CSS Selectors

At very basic css is selecting an element and applying styles to it. In this article we will see how do we select elements with css.

CSS Selectors

Type Selector

  • The most basic kind of selector, simple matching pattern.
h1 {
  color: blue;
}

Universal Selector

  • Matches to all elements, of any type
/* Applies a border to all elements */
* {
  border: 1px solid black;
}

Class and Id Selectors

Type selectors are too general there are two attributes that are used to add extra information to any HTML Element Class and ID.

How to use class selector

  1. Add the class attribute to the HTML element.
  2. You define the value of class attribute.
  3. This value will become the selector, starting with a period.
  4. Resuable
  5. Can be applied to any element.
  6. Selector only matches with the name/value of the class.

How to use multiple classes

<p class="fancy intro"> Fancy intro paragraph.</p>
/* only fancy styles */

.fancy {
  ....;
}

/*  only intro styles  */

.intro {
  ....;
}
/* only applies if "fancy" AND "intro* are present */

.fancy.intro {
  ....;
}

How to use ID Selector

  • Add the ID attribute to the HTML element.
  • You define the value of ID attribue.
  • The value of ID becomes the selector, starting with a # symbol.
  • ID can only be used once per page.

IDs use for In-Page Linking

  • Can be used for CSS and in-page linking.
/* In-Page Linking */

<a href="#example"> Links to a spot on the page</a>
<section id="example">Link goes here</section>
Some people don’t use IDs at all, they use classes for style and IDs only for In-Page Linking.

Naming Conventions

  • Instead of spaced, use a hyphen or underscore.
  • Use meaningfull and descriptive names.
  • Use easily understood abbreviations.
Previous
Next