The importance of blending classes versus isolating classes in CSS selectors

Could somebody please direct me to the CSS hierarchy rules concerning "concatenated classes" versus "separated classes"?

Furthermore, what are the correct terms for "concatenated classes" versus "separated classes" (I suspect that is why the documentation I am looking for remains elusive.)

For instance, in the CSS provided below, .row .second (with a space) seems to have higher precedence than .row.second (without a space), despite both matching 2 class attributes.

.row {
  width: 150px;
  background-color: lightgray;
  margin: 15px;
}

section {
  margin-left: 15px;
}

.row .second {
  color: purple;
}

.row.second {
  color: orange;
}

When applied to the following HTML, the above CSS yields this outcome: https://i.sstatic.net/acKxF.png

Why is "Stuff 2b" displayed in purple instead of orange? (In simpler terms, why does .row .second take precedence over .row.second in this scenario?)

<div id='outerBox'>
<div class="row">
  <div class="title">
  Row 1 Title
  </div>
  
  <section>
    Stuff 1a
  </section>

  <section class='second'>
    Stuff 1b
  </section>

  <section>
    Stuff 1c
  </section>
</div>

<div class="row second">
  <div class="title">
  Row 2 Title
  </div>
  
  <section>
    Stuff 2a
  </section>

  <section class='second'>
    Stuff 2b
  </section>

  <section>
    Stuff 2c
  </section>
  </div>
  
  <div class="row">
  <div class="title">
  Row 3 Title
  </div>
  
  <section>
    Stuff 3a
  </section>

  <section class='second'>
    Stuff 3b
  </section>

  <section>
    Stuff 3c
  </section>
  
</div>
</div>

(The CSS mentioned here is being used on the HTML provided above in JSFiddle on Chrome for MacOS.)

Answer №1

Using separate classes for styling child elements in CSS is a common practice. For example:

.row .red # This targets red child elements within the row
{
  color:red;
}
<tr class="row">
   <td class="red">
      <p>Hey!</p> ### The text color of this paragraph will be red.
   </td>
</tr>

The elements with the class name "red" within the ".row" class will have a red color.

However, concatenated classes are used when specifying an element with multiple classes together like "with".

Let me provide an example:

.row.red # This targets elements with both "row" and "red" classes
{ 
  color:red;
}
<tr class="row">
   <td class="red">
      <p>Hey!</p> # The color of this paragraph will not be red.
   </td>
</tr>

<tr class="row red">
   <td class="">
      <p>Hey!</p> # However, this paragraph will be styled in red.
   </td>
</tr>

Answer №2

Although commonly used, classes do not relate to Object Orientation. This means that there is no object-oriented mechanism for 'concatenating/separating' elements. It essentially serves as a syntax for defining different types of CSS selectors. I often view CSS definitions as an elaborate list of conditional if-statements.

  • without space, .row.second: includes all .row elements that also have the class .second
  • with space, .row .second: selects all .row elements that contain child elements with the class .second, regardless of nesting level.

This implies that there is no specific hierarchy at play in this scenario. You are either targeting any second row element or any second child element within a row element.

Your confusion might stem from the difference in notation between CSS and HTML tags:

<tag class="row second">
with space is different from .row .second { ... } which also contains spaces, but they are equivalent to .row.second { ... } without spaces. Essentially, it represents a <tag> that has both the classes .row and .second.

In CSS, spaces signify selecting parent elements with the class .row and then selecting their child elements with the class .second.

Update

I failed to mention (as @TemaniAfif did) that the property color is inherited from the parent, assuming that OP already knew this.

Displayed below are various examples showcasing different scenarios:

div>* {
  background-color: lightgray;
  margin: 15px;
}

/* default styling */
.row, .default1    { color: purple }
.second, .default2 { color: orange }

/* exceptions in special cases */
.row.second, .exception1  { color: green }
.row .second, .exception2 { color: red }
<p><b>Legend:</b> explanation per parent class used and (rule that applies)</p>

<h3>no parent class</h3>
 <div>
   <div>no class, will inherit document default styling</div>
   <div class="row">row, styled in purple (default1)</div>
   <div class="second">second, styled in orange (default2)</div>
   <div class="row second">row second, styled in green (exception1)</div>
</div>

<h3>.row parent</h3>
<div class="row">
   <div>no class, inherits purple styling from the parent (default1)</div>
   <div class="row">row, styled in purple like its parent (default1)</div>
   <div class="second">second, styled in red as it is a child of row (exception2)</div>
   <div class="row second">row second, styled in red, overrides parent styling (exception2)</div>
</div>

<h3>.second parent</h3>
<div class="second">
   <div>no class, inherits orange styling from the parent (default2)</div>
   <div class="row">row, styled in purple, overrides parent styling (default1)</div>
   <div class="second">second, styled in orange just like its parent (default2)</div>
   <div class="row second">row second, styled in green, overrides parent styling (exception1)</div>
</div>

<h3>.row .second parent</h3>
<div class="row second">
   <div>no class, styled in green inherited from parent (exception1)</div>
   <div class="row">row, styled in purple overriding parent styling (default1)</div>
   <div class="second">second, styled in red as a child of row (exception2)</div>
   <div class="row second">row second, styled in red, overrides parent styling (exception2)</div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The vertical tab layout in HTML and CSS is experiencing an issue where the active tab is not being shown above the

Currently, I am developing a web page featuring vertical tabs where each tab corresponds to an image and some content. However, the problem lies in the fact that the active tab is not displaying above the image as expected. In my attempt to resolve this i ...

Angular JS is having some issues with rendering the style correctly

How can I make input fields turn pink before values are entered and green after values are entered? Currently, the styling only applies to the first row. What could be causing this issue? <script src="https://ajax.googleapis.com/ajax/libs/angularjs ...

elevate design css/widget/components

I am currently on the lookout for samples of boot strap floating css/widget/parts. Despite googling with keywords like 'floating / fixed', I have only come across sticky footer and header examples, or some simple panel samples. By 'floatin ...

Animated CSS side panel

I'm currently working on creating an animation for a side menu. The animation works perfectly when I open the menu, but the problem arises when I try to animate it back closed. Is there a property that allows the animation to play in reverse when the ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

What is the best way to ensure that all elements on an HTML webpage stay centered regardless of zoom level?

My HTML and CSS skills are not at an expert level. Despite my best efforts, when I zoom in on the webpage I created, certain elements like the logo and language switcher appear broken. I'm unsure how to address this issue. Can someone please provide m ...

Not all Angular Material2 styles are being fully applied

One issue I am encountering is that styles for components such as <mat-chip> or <button mat-raised-button> (the only ones I have found) are not working properly and appear gray by default. However, styles do apply correctly to the <mat-card& ...

Automatically adjusting input box size and position in real-time

I am working on a form that includes a button and an input field. When the user clicks on the button "ADD MORE FIELDS," I want to dynamically generate a new input box. Although I have tried using code from this jsfiddle link and it works, my goal is to ach ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

Utilize custom {tags} for replacing strings in a CSS file using str_replace in PHP

My code consists of a script that updates a CSS file based on user input from an html form. The script executes a str_replace function, scanning the CSS file for specific "tags". For example: html,body { background: {bgcolor} url(../images/bg.jpg) re ...

Scrollable content below the div

I have encountered an issue where a div is positioned above another div, and when I scroll the upper div to the bottom, it ends up scrolling the entire body. To better illustrate this problem, I have created a demo on JSFiddle: http://jsfiddle.net/2Ydr4/ ...

Employ CSS to target the initial and final items within sets of identical elements

I created the following CSS styles: div { width: 300px; text-align: center; } p:not(.vrt) { text-align: left; } p.vrt { writing-mode: vertical-rl; display: inline-block; } div :nth-child(1 of p.vrt) { margin-left: 0; } div :nth-last-child(1 of ...

Floating and scrolling navigation bar not functioning properly in bootstrap framework

I've been dabbling in coding for a while now, practicing at my current job. I managed to create a floating and scrolling navigation bar on the right side of my website using bootstrap. However, after taking a 3-week break and returning to my site, I n ...

What are some strategies for efficiently positioning buttons using CSS to prevent unwanted consequences?

Below is the CSS and HTML code, detailing a specific issue. * { box-sizing: border-box; font-family: Georgia, 'Times New Roman', Times, serif; } body { margin: 0; font-family: Georgia, 'Times New Roman', Times, serif; } .topn ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

concealing components during screen adjustments

There are 3 identical <div>s available: <div class="box">Hello World!</div> <div class="box">Hello World!</div> <div class="box">Hello World!</div> I need these <div>s to ...

Is it possible to utilize CSS rules for a non-existent div within CSS?

Can this be achieved using CSS? If .div1 is not present, enforce the following rule: .div2{ property: value; } For example, <div class="div1"> ... </div> <div class="div2"> <!-- it exists, so no action needed --> </div& ...

Stretch the div to the right and maintain its horizontal width

I am in the process of coding a two-column layout, with a total width of 980px. Each column will have a background that expands all the way to the left and right sides as shown in the screenshot here. On the left side, there is a blue div with a width of ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

Align columns to the right and left using Bootstrap

It should be simple enough, but I can't seem to find my mistake. Goal: The entire markup should be centered with a width of col-10. Within the same 10-column width, there should be two divs each taking up 50% of the space. Using Bootstrap 5, for so ...