Everything You Need to Know about ID in CSS (2024)

HTML elements can be defined by type, class, attribute, pseudo-state, or ID name. How you define them will affect how you customize them using CSS selectors.

Everything You Need to Know about ID in CSS (1)

For example, if you want to make broad changes on your site, then you can use a type selector. Say you’d like to style every span element on your site with CSS. Then you’d use the type selector span { style properties }.

To make more detailed changes, you need a more specific selector. The most specific is an ID selector. Let’s take a closer look at this selector type below.

CSS ID selector

A CSS ID selector uses the ID attribute of an HTML element to select one unique element on a page. To use an ID selector in CSS, you simply write a hashtag (#) followed by the ID of the element. Then put the style properties you want to apply to the element in brackets.

Here’s a look at the syntax of an ID selector in CSS:

#idname { style properties }

There are a few rules you must follow to use the CSS ID selector correctly. Before we take a look at those rules below, let me make an important note about the examples below.

I’ll also be using BootstrapCDN to load Bootstrap's default stylesheet so the examples will be styled accordingly. However, the HTML and CSS of the examples will work on HTML5 sites as well. So if you’re building your site from scratch instead of using the Bootstrap CSS framework, you can still use the HTML and CSS as templates.

Everything You Need to Know about ID in CSS (3)

Free Guide: 25 HTML & CSS Coding Hacks

Tangible tips and coding templates from experts to help you code better and faster.

  • Coding to Convention
  • Being Browser-Friendly
  • Minimizing Bugs
  • Optimizing Performance
Learn more

    Download Free

    All fields are required.

    How to Use ID in CSS

    The first rule to keep in mind when using the ID attribute is that it must contain at least one character and cannot begin with a number.

    Let’s say I have multiple h2s on my site and each marks the start of a new chapter. Then I might give each h2 an ID name.

    The following HTML is correct:

    <h2 id="C1">Chapter 1</h2><h2 id="C2">Chapter 2</h2><h2 id="C3">Chapter 3</h2><h2 id="C4">Chapter 4</h2>

    This is incorrect:

    <h2 id="1">Chapter 1</h2><h2 id="2">Chapter 2</h2><h2 id="3">Chapter 3</h2><h2 id="4">Chapter 4</h2>

    The second rule to keep in mind is that if an element is given an ID name, it must be unique within a page. That way, an ID selector selects only one unique element.

    Returning to the example of multiple h2s, let’s say I want each of these h2s to have a different style to visually cue the reader when a new chapter begins. In that case, I’d give each h2 a unique ID name so that I could use ID selectors to apply a unique set of property values to each.

    The following HTML is correct:

    <h2 id="C1">Chapter 1</h2><h2 id="C2">Chapter 2</h2><h2 id="C3">Chapter 3</h2><h2 id="C4">Chapter 4</h2>

    This is incorrect:

    <h2 id="C4">Chapter 1</h2><h2 id="C4">Chapter 2</h2><h2 id="C4">Chapter 3</h2><h2 id="C4">Chapter 4</h2>

    The following CSS would change the font size of each h2:

    #C1 { font-size: 18px;}#C2 { font-size: 20px;}#C3 { font-size: 22px;}#C4 { font-size: 24px;}

    Here’s the result:

    See the Pen mdWVXKM by Christina Perricone (@hubspot) on CodePen.

    The last rule to keep in mind when using ID selectors is that the property value of the ID selector must match the ID name exactly.

    Using the HTML from the example above, the following CSS would be correct.

    #C1 { font-size: 18px;}#C2 { font-size: 20px;}#C3 { font-size: 22px;}#C4 { font-size: 24px;}

    This would be incorrect:

    #c1 { font-size: 18px;}#c2 { font-size: 20px;}#c3 { font-size: 22px;}#c4 { font-size: 24px;}

    If I were to use this CSS with the lowercase “c,” the CSS ID selectors and their respective CSS rules would not be applied. The default h2 style in Bootstrap would render instead, as shown below.

    See the Pen How NOT to use CSS ID [Example] by Christina Perricone (@hubspot) on CodePen.

    We've covered the rules of using the ID selector in CSS. Now let's apply them by using an ID selector to style images.

    CSS Image ID

    You can use the ID selector on headings or images, buttons, and other HTML elements.

    Let's say you want to style a specific image on your page. Maybe you want it to have a different shape and level of opacity than the other images on that page. In that case, you could use an ID selector.

    To start, you'd add an ID attribute to the image. This ID attribute can appear anywhere inside the image element: before the img src attribute, after the src attribute but before the alt attribute, after both the img src and alt attributes.

    In the example below, I'll place the ID attribute "round" before the src and alt attributes in the second image element. Then, I'll use an ID selector to style this image to be round and 70% opaque.

    Here's the HTML:

    <img src="https://source.unsplash.com/fk4tiMlDFF0/300x200/" alt="tiniest puppy"><img id="round" src="https://source.unsplash.com/TzjMd7i5WQI/300x200/" alt="tiny puppy"><img src="https://source.unsplash.com/-Go4DH2pZbc/300x200/" alt="least tiny but still tiny puppy">

    Here's the CSS:

    #round { border-radius: 50%; opacity: 0.7;}

    Here's the result:

    See the Pen CSS Image ID by Christina Perricone (@hubspot) on CodePen.

    Now that we understand what an ID selector is and how to use one in CSS, let’s make sure we understand the distinction between class and ID in CSS.

    CSS Class vs ID

    In CSS, a class is used to group more than one element, whereas an ID is used to identify a single element. A class selector is therefore used to style multiple HTML elements of the same class, while an ID selector is used to style one HTML element. You can recognize a class selector by the period (“.”) it contains and an ID selector by the hash character (“#”)

    Another key difference between a class selector and an ID selector is specificity. CSS selectors have different levels of specificity so that if an HTML element is targeted by multiple selectors, the browser will apply the CSS rule of the selector with the higher specificity.

    When comparing class selectors vs. ID selectors, ID selectors have the higher specificity and are therefore more powerful. (In fact, ID selectors are so powerful that only the !important property can override them in CSS.) That means if an element is targeted by an ID selector and a class selector, the CSS style of the ID selector will be applied to the element over the style of the class selector.

    Let’s take a look at an example demonstrating this rule below.

    Say I’m creating buttons for my Bootstrap site. While Bootstrap CSS offers predefined styles for buttons, I’m going to create custom ones so I just start with the most basic template, shown below.

    Here's the CSS:

    <button type="button" class="btn">Button copy</button>

    Across my site, I want my button elements to be Calypso blue. In that case, I’d use a class selector to define all elements under the button class to have a blue background color (the hex color code #00A4BD) and a white font color (#FFFFFF).

    Everything You Need to Know about ID in CSS (5)

    Free Guide: 25 HTML & CSS Coding Hacks

    Tangible tips and coding templates from experts to help you code better and faster.

    • Coding to Convention
    • Being Browser-Friendly
    • Minimizing Bugs
    • Optimizing Performance
    Learn more

      Download Free

      All fields are required.

      Everything You Need to Know about ID in CSS (6)

      You're all set!

      Click this link to access this resource at any time.

      Download Now

      Here’s the HTML:

      <button type="button" class="btn">Subscribe</button><button type="button" class="btn">Subscribe</button>

      Here’s the CSS:

      .btn { background-color: #00A4BD; color: #FFFFFF;}

      Here’s the result:

      See the Pen qBrbxwa by Christina Perricone (@hubspot) on CodePen.

      But let’s say I want the subscribe button on my homepage to be even more eye-catching. Then I could use an ID selector to define the one button with the ID “homepage” and style it to have a fuschia background color and a black font color (#000000). All buttons without the ID “homepage” will still follow the CSS rule of the class selector (blue background color and white font color).

      Here’s the HTML:

      <button type="button" class="btn" id="homepage">Subscribe</button><button type="button" class="btn">Subscribe</button>

      Here’s the CSS:

      #homepage { background-color: #FF00FF; color: #000000;}.btn { background-color: #00A4BD; color: #FFFFFF;}

      Here’s the result:

      See the Pen CSS Class vs ID [Example] by Christina Perricone (@hubspot) on CodePen.

      Make Detailed Changes with the CSS ID Selector

      CSS selectors enable you to control the appearance of HTML elements on your site. With the ID selector, you can maintain granular control over your customization process and code by targeting a single element on the page. To use this selector, you only need basic knowledge of HTML and CSS.

      Editor's note: This post was originally published in May 2020 and has been updated for comprehensiveness.

      Everything You Need to Know about ID in CSS (2024)

      FAQs

      What is the rule for ID CSS? ›

      A CSS ID selector uses the ID attribute of an HTML element to select one unique element on a page. To use an ID selector in CSS, you simply write a hashtag (#) followed by the ID of the element.

      What does an ID do in CSS? ›

      The CSS ID selector matches an element based on the value of the element's id attribute. In order for the element to be selected, its id attribute must match exactly the value given in the selector.

      Is it okay to use ID selectors for styling purposes? ›

      Both ID's and classes are perfectly fine to use for CSS styling. Use ID's for unique elements. In other words, each ID should not be used more than once.

      Why is ID unique in CSS? ›

      IDs should be unique on a page. This means that if you attach a style to an ID, you won't be able to reuse it within the same webpage. Classes, however, can appear on several HTML elements on the same page. Being able to reuse styles is one of the advantages of CSS.

      Can you have two IDs in CSS? ›

      You are correct, you should only have one id per element. ID's and classes also have different css specificity, which is why it's so common to find classes as the main selector for css styles, as they have 1 point, vs an id that carries 10 points - the goal is to always keep css specificity as low as possible.

      How to target an ID in CSS? ›

      The CSS id Selector

      The id selector uses the id attribute of an HTML element to select a specific element. The id of an element is unique within a page, so the id selector is used to select one unique element! To select an element with a specific id, write a hash (#) character, followed by the id of the element.

      What is the difference between class and ID in CSS? ›

      While an ID is specific to a single element, classes can be assigned to multiple elements on a page or throughout the website. They are not unique. And while a single element can only have one ID, it can have multiple classes.

      Can I use class and ID together? ›

      Yes, you can use "class" and "id" together without any problems. The only recommendation is to always use unique "id" names. Never use the same "id" name more than once.

      Why do we use ID? ›

      ID is meant to identify element uniquely either in javascript or css or any other framework. So if you are not targetting the elements you don't need to give ids, But for your understanding you can give meaningful ids for code readability.

      Why is ID not recommended as a selector? ›

      However, it's important to note that using ID selectors for styling in AEM is generally not recommended because it can lead to specificity conflicts and cause maintenance issues. Instead, AEM encourages the use of class-based selectors and component hierarchy for styling components.

      How many times can you use a ID selector? ›

      The major difference is that IDs can only be applied once per page, while classes can be used as many times on a page as needed. “ if you want to apply same css to multiple html elements, use class. just define a class in css, write all stylings and then give that class to all elements you want to style same.

      What is the purpose of a style ID? ›

      The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.

      Is it good practice to use id in HTML? ›

      While you can technically use classes for unique identification, it's considered best practice to reserve IDs for elements that should only appear once on a page. This helps maintain clarity in your code and can be useful for JavaScript interactions where you specifically target a unique element.

      Can we use same ID in CSS? ›

      It is not recommended to use the same ID name for different elements or assign multiple IDs to a single element in web development, specifically in HTML and CSS. This practice violates the principles of uniqueness and clarity, making it harder to target elements accurately and maintain a structured codebase.

      How to give a div an ID? ›

      Replace element with the HTML tag for the specific element you want to add the id to, like div or p . Replace your-id with the desired id name. This will allow you to selectively style or manipulate that specific element using CSS or JavaScript. In this example, the id of the div is set to "main-content".

      What characters are allowed in CSS ID? ›

      In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

      Can CSS ID have spaces? ›

      An ID attribute's value must not contain ASCII whitespace characters. Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID.

      How to create an ID card in HTML and CSS? ›

      HTML
      1. <div class="id-card-tag"></div>
      2. <div class="id-card-tag-strip"></div>
      3. <div class="id-card-hook"></div>
      4. <div class="id-card-holder">
      5. <div class="id-card">
      6. <div class="header">
      7. <img src="https://is4-ssl.mzstatic.com/image/thumb/Purple118/v4/62/cd/f5/62cdf5b2-a731-76ca-aa69-fe82c8a09d94/source/512x512bb.jpg">
      8. </div>

      Top Articles
      Pyramid Schemes
      What to know when taking out a life insurance policy on someone else
      Hotels Near 6491 Peachtree Industrial Blvd
      neither of the twins was arrested,传说中的800句记7000词
      No Hard Feelings Showtimes Near Metropolitan Fiesta 5 Theatre
      Ixl Elmoreco.com
      Free Atm For Emerald Card Near Me
      Air Canada bullish about its prospects as recovery gains steam
      Simple Steamed Purple Sweet Potatoes
      Washington, D.C. - Capital, Founding, Monumental
      Superhot Unblocked Games
      Healing Guide Dragonflight 10.2.7 Wow Warring Dueling Guide
      Xxn Abbreviation List 2023
      Aspen Mobile Login Help
      Delaware Skip The Games
      If you bought Canned or Pouched Tuna between June 1, 2011 and July 1, 2015, you may qualify to get cash from class action settlements totaling $152.2 million
      Leccion 4 Lesson Test
      Drift Boss 911
      Maxpreps Field Hockey
      Ivegore Machete Mutolation
      Yonkers Results For Tonight
      Sound Of Freedom Showtimes Near Movie Tavern Brookfield Square
      Umn Biology
      Pokémon Unbound Starters
      WPoS's Content - Page 34
      Tim Steele Taylorsville Nc
      What is Software Defined Networking (SDN)? - GeeksforGeeks
      Trust/Family Bank Contingency Plan
      Frequently Asked Questions - Hy-Vee PERKS
      Lincoln Financial Field, section 110, row 4, home of Philadelphia Eagles, Temple Owls, page 1
      Arcadia Lesson Plan | Day 4: Crossword Puzzle | GradeSaver
      Mydocbill.com/Mr
      Craigslist Pets Huntsville Alabama
      Pokemon Reborn Locations
      Karen Wilson Facebook
      Electric Toothbrush Feature Crossword
      Www.craigslist.com Waco
      LoL Lore: Die Story von Caitlyn, dem Sheriff von Piltover
      Grizzly Expiration Date Chart 2023
      Penny Paws San Antonio Photos
      Mychart University Of Iowa Hospital
      Mynord
      Breaking down the Stafford trade
      Random Warzone 2 Loadout Generator
      El Patron Menu Bardstown Ky
      Ret Paladin Phase 2 Bis Wotlk
      How Did Natalie Earnheart Lose Weight
      Vt Craiglist
      All Obituaries | Roberts Funeral Home | Logan OH funeral home and cremation
      Heisenberg Breaking Bad Wiki
      Latest Posts
      Article information

      Author: Catherine Tremblay

      Last Updated:

      Views: 5921

      Rating: 4.7 / 5 (67 voted)

      Reviews: 90% of readers found this page helpful

      Author information

      Name: Catherine Tremblay

      Birthday: 1999-09-23

      Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

      Phone: +2678139151039

      Job: International Administration Supervisor

      Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

      Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.