Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

CSS Basic

CSS Selectors

Posted in CSS Tutorial
Updated on Sep 07, 2024
By Mari Selvan
πŸ‘οΈ 12 - Views
⏳ 4 mins
πŸ’¬ 0
CSS Selectors

Photo Credit to CodeToFun

πŸ™‹ Introduction

CSS selectors are patterns used to select elements on a web page to apply styles. They help define the look and layout of a website by targeting specific HTML elements.

❓ What Are CSS Selectors?

CSS selectors allow you to apply styles to specific HTML elements based on their type, class, ID, or other attributes. By using selectors, you can control the appearance of your web content without altering the HTML structure.

πŸ“‘ Table of Contents

The following are the list of CSS Selectors

SelectorExplanationDescription
.class .demo Selects all elements with class="demo"
.class1.class2 .name1.name2 Targets elements that have both name1 and name2 classes.
.class1 .class2 .name1 .name2 Targets elements with the class name2 that are descendants of elements with the class name1.
#id #rollNo Targets an element with a specific id attribute, ensuring unique styling for that element.
* * Applies styles to all elements on a page.
element p Targets and styles all instances of a specified HTML element.
element.class p.demo Targets elements of a specified type with a given class name for styling.
element,element div, p Applies styles to multiple elements listed, separating them by commas.
element element div p Targets nested elements by specifying one element type followed by another, styling elements that are children of a specified parent element.
element>element div > p Targets direct child elements of a specified parent element.
element+element div + p Targets an element that immediately follows a specified element, allowing for styling of adjacent siblings.
element1~element2 p ~ ul Targets element2 elements that are preceded by element1 siblings in the same container.
[attribute] [target] Targets elements with a specific attribute, allowing you to apply styles based on the presence of that attribute.
[attribute=value] [target="_blank"] Targets elements with a specific attribute value, allowing for precise styling based on attribute presence and value.
[attribute~=value] [title~="apple"] Targets elements whose specified attribute contains a value that matches a word within a space-separated list.
[attribute|=value] [lang|="en"] Targets elements with an attribute value that starts with the specified value, followed by a hyphen, or exactly matches it.
[attribute^=value] a[href^="https"] Targets elements with an attribute value that starts with the specified value.
[attribute$=value] a[href$=".pdf"] Targets elements with an attribute whose value ends with the specified value.
[attribute*=value] a[href*="codetofun"] Targets elements with an attribute whose value contains a specified substring.
:active a:active Styles elements while they are being activated by user interaction, such as when a link is clicked.
::after p::after Inserts content after an element's existing content, allowing for additional styling and effects.
::before p::before Inserts content before an element’s existing content, allowing for additional styling or decorations.
:checked input:checked Targets form elements that are checked or selected, such as checkboxes and radio buttons.
:default input:default Targets form elements that are in their default state, such as the initially selected option in a dropdown.
:disabled input:disabled Targets form elements that are disabled, allowing you to style them accordingly.
:empty p:empty Targets elements with no child content, including text or elements, for styling.
:enabled input:enabled Targets form elements that are enabled and can be interacted with, such as inputs or buttons.
:first-child p:first-child Targets the first child element within its parent, allowing specific styling for that element.
::first-letter p::first-letter Styles the first letter of a block-level element, allowing for custom typography effects.
::first-line p::first-line Styles the first line of text within a block-level element.
:first-of-type p:first-of-type Targets the first element of its type within its parent for styling.
:focus input:focus Styles elements that have keyboard or mouse focus, such as input fields and links.
:fullscreen :fullscreen Applies styles to an element when it is in fullscreen mode.
:has() h2:has(+p) Applies styles to elements based on their descendants, allowing conditional styling based on the presence of child elements.
:hover a:hover Applies styles to an element when the mouse pointer is over it.
:in-range input:in-range Targets form elements whose value is within a specified range.
:indeterminate input:indeterminate Applies styles to input elements that are in an indeterminate state, such as checkboxes with a mixed selection.
:invalid input:invalid Targets form elements with invalid input, such as incorrect data or unmet constraints.
:lang() p:lang(it) Applies styles to elements with the specified language attribute, in this case, Italian.
:last-child p:last-child Targets the last child element of its parent.
:last-of-type p:last-of-type Targets the last element of its type within its parent, allowing for specific styling of that element.
:link a:link Styles unvisited links.
::marker ::marker Targets the marker box of list items, allowing you to style list bullets or numbers.
:not() :not(p) Applies styles to elements that do not match a given selector.
:nth-child() p:nth-child(2) Targets elements based on their position in a parent element, allowing for styling of specific child elements according to a pattern or formula.
:nth-last-child() p:nth-last-child(2) Targets elements based on their position from the end of their parent container.
:nth-last-of-type() p:nth-last-of-type(2) Targets elements of a specific type based on their position from the end of their parent.
:nth-of-type() p:nth-of-type(2) Targets elements of a specified type based on their position within a parent, allowing for advanced pattern-based styling.
:only-of-type p:only-of-type Targets elements that are the only one of their type among their siblings.
:only-child p:only-child Targets an element that is the only child of its parent.
:optional input:optional Targets input elements with no required attribute, allowing for styling of non-mandatory fields.
:out-of-range input:out-of-range Styles input fields with values that are outside a specified range.
::placeholder input::placeholder Styles the placeholder text within input and textarea elements.
:read-only input:read-only Targets form elements that are not editable by the user.
:read-write input:read-write Targets elements that are editable or modifiable by the user.
:required input:required Targets form elements that are required to be filled out before submission.
:root :root Targets the highest-level parent element, usually the element, for defining global CSS variables.
::selection ::selection Styles the portion of a document that a user has highlighted or selected.
:target #news:target Applies styles to the element that matches the current URL fragment identifier (e.g., #news).
:valid input:valid Selects all input elements with a valid value
:visited a:visited Selects all visited links

πŸ“ Example Usage

Here’s a simple example that demonstrates the use of element, class, and ID selectors:

example.scss
Copied
Copy To Clipboard
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Selectors Example</title>
  <style>
    /* Element selector */
    p {
      color: blue;
    }

    /* Class selector */
    .highlight {
      background-color: yellow;
    }

    /* ID selector */
    #footer {
      text-align: center;
    }
  </style>
</head>
<body>
  <p>This is a paragraph.</p>
  <p class="highlight">This is a highlighted paragraph.</p>
  <div id="footer">Footer Text</div>
</body>
</html>

βœ… Best Practices

  • Use Classes Over IDs: Classes are more flexible and reusable compared to IDs.
  • Limit Use of Universal Selectors: Avoid using the universal selector (*) unless absolutely necessary, as it can negatively impact performance.
  • Keep Specificity Low: Lower specificity makes CSS easier to maintain. Use specific selectors only when necessary.

⚠️ Common Pitfalls

  • Overusing ID Selectors: ID selectors can quickly lead to specificity issues, making styles difficult to override.
  • Not Considering Selector Performance: Deep descendant selectors like div div div p can slow down rendering, especially in complex layouts.
  • Incorrect Use of Pseudo-Classes: Pseudo-classes like :hover won’t work on mobile devices unless carefully managed.

πŸŽ‰ Conclusion

CSS selectors are fundamental to web development, enabling you to precisely target and style HTML elements.

By mastering different types of selectors, you can create efficient, maintainable, and high-performing stylesheets for your websites.

πŸ‘¨β€πŸ’» Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
πŸ‘‹ Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy