When writing CSS, we typically select HTML elements using their classes (.class-name) or IDs (#id-name). But in this guide, we will show you how to style HTML tag without class or id using standard CSS selectors. What happens when you encounter a generic HTML tag inside a layout that has absolutely no class, ID, or custom attributes assigned to it?
For example, look at this common HTML structure:
html
<section>
<div>Target This Element</div> <!-- No Class, No ID -->
<div class="active">Item 2</div>
<div id="featured">Item 3</div>
</section>
If you want to style only the first <div> without modifying the HTML structure or adding temporary hacks, you must rely on standard, valid CSS selection strategies.
In this tutorial, we will cover the two most reliable and professional methods to achieve this without using invalid attribute hacks.
Also Read: How to Fix “CSS Error: Expected ‘:’ but found ‘/’. Declaration dropped
Method 1: Using Structural Pseudo-Classes (The No-HTML-Change Solution)
If you cannot alter the HTML code (for instance, when working with a third-party CMS or plugin template), the best approach is to leverage structural selectors.
Since the target element is the first <div> inside its parent <section>, we can precisely target it using the standard :first-of-type or :first-child pseudo-class combinators.
Here is the clean, verified code snippet. You can copy this code directly via your code block wrapper:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Structural Selector Example</title>
<style>
/* Selects the very first div child immediately inside the section */
section > div:first-of-type {
background-color: #ffeb3b;
color: #000000;
padding: 10px;
font-weight: bold;
border-left: 5px solid #f44336;
}
</style>
</head>
<body>
<section>
<div>1. This generic div is targeted perfectly using :first-of-type.</div>
<div class="active">2. This div has a class attribute.</div>
<div id="featured">3. This div has an ID attribute.</div>
</section>
</body>
</html>
Method 2: Adding a Dedicated Class Name (The Best Practice Solution)
While structural pseudo-classes work well, they break easily if the position of the elements inside the HTML changes later. If you have access to modify the HTML file, the most scalable and bulletproof web development standard is to add a descriptive class name.
Updated HTML:
html
<section>
<div class="target-element">Target This Element</div>
<div class="active">Item 2</div>
<div id="featured">Item 3</div>
</section>
Corresponding CSS:
CSS
.target-element {
background-color: #ffeb3b;
color: #000000;
padding: 10px;
}
Why this is preferred: Explicit class selectors make your stylesheets highly maintainable, predictable, and clean for future updates or team collaborations.