Can you explain the distinction between using .classA versus .classB.classA when styling with CSS?

When I use .show instead of .box.show in the CSS, the even boxes do not come from the left side. This discrepancy has left me puzzled as I assumed they would have the same effect. However, it appears that in this particular code snippet, they are behaving differently.

const boxes = document.querySelectorAll('.box');

window.addEventListener('scroll',()=>{
    const triggerPoint=window.innerHeight*4/5;
    boxes.forEach((box)=>{
        const boxTop=box.getBoundingClientRect().top;
        if(boxTop<triggerPoint){
            box.classList.add('show')
        }else{
            box.classList.remove('show')
        }
    })
})
*{
    padding:0;
    margin:0;
    box-sizing: border-box;
}


body{
    background-color: #efedd6;
    min-height: 100%;
    width:100%;
    display:flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    overflow-x: hidden;
}

.box{
    width: 100px;
    height: 100px;
    background-color: rgb(226, 43, 43);
    margin:10px;
    transform: translateX(4000%);
    transition:0.4s;
}

h1{
    margin:10px;
}



.box:nth-of-type(even){
    transform: translateX(-4000%);
}
.box.show{
    transform: translateX(0%);
    transition: .4s;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Scroll Animation</title>
</head>
<body>
    <!-- <h1>scroll to see the Animation</h1> -->
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>


    <script src="main.js"></script>
</body>
</html>

Answer №1

.classA is used to target elements with the CSS class classA and has a CSS specificity of 0, 0, 1, 0 which equals 10 in this case.

classA.classB (or .classB.classA) targets elements with both classes classA and classB, boosting its specificity to 20 (due to two classes).

Understanding these specifics is crucial for your situation.

Your default transform selector below has a specificity of 10:

.box{
  transform: translateX(4000%);
}

Whereas, the following selector

.box:nth-of-type(even){
   transform: translateX(-4000%);
}

possesses a specificity of 20, allowing it to override similar CSS attributes from selectors with lower specificity. This explains why your even animation overrides

.box{transform: translateX(4000%);}
.

However,

.show{ transform: translateX(0%); }
lacks higher specificity, potentially leading to an override failure of the original value.

On the other hand,

.box.show{transform: translateX(0%);}
has a specificity of 20 and will definitely replace the original value like the selector for even elements.

To delve deeper into the concept of specificity, check out this detailed guide with visual aids: specifics-on-css-specificity

Answer №2

The concept of selector specificity is crucial to understanding CSS (https://www.w3.org/TR/selectors-3/#specificity)

When inspecting the .show element in developer tools, you'll notice that the transform style is overridden by the .box:nth-of-type(even) class due to the higher specificity of the pseudo-class :nth-of-type.

For a visual demonstration, visit

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

Looking for assistance with a PHP program that involves if-else statements

<HTML> <body> <?php echo "<H4>Do you identify as male?</h4>" ?> <form action ="ifstat.php" method ="post"> Please enter your response: <input type="text" name="val1"> <input type ="submit" > <inp ...

The command 'create-react-app' is not valid and cannot be recognized as an internal or external command, operable program, or batch file

I've been struggling to set up a React project, as the create-react-app my-app command doesn't seem to be working. Can anyone offer some assistance? Here are the commands I'm using: npm install -g create-react-app create-react-app my-app ...

Explore various SVG paths by hovering to reveal or conceal different divs

Hi there, I'll do my best to explain clearly. If this question has already been asked, I apologize as I couldn't find an answer when searching. I've used SVG to create a map on my HTML webpage and it's looking great. I also have hidden ...

What are the steps to resolve the "undefined cannot read property push" error in Node.js?

While attempting to learn Nodejs, I created a simple app. However, when I run "nodemon index.js" in the command prompt, I encountered the following error: TypeError: Cannot read property 'push' of undefined The app crashed and is now waiting for ...

please transmit the id (or retrieve the id from the router path)

I have a basic blog built with React/Redux for the frontend, featuring user registration and articles. I ran into an issue when trying to pass the article ID to the editor component. The form is the same, but the paths differ for adding new articles and ed ...

Is it possible to avoid widows in CSS without the need for extra HTML elements?

I have a snippet of text that is controlled within a Content Management System. The CMS restricts the use of HTML or special characters such as &nbsp; or <span>. Despite my attempts to adjust margins and padding, I cannot achieve the desired out ...

Convert a rendered Django template into Json and include additional elements

Imagine a scenario where there is a view connected to a template, passing some context data (i.e. objects) to be rendered in the HTML output displayed in the browser. The typical view setup would look something like this: # views.py def view_name(request ...

Issues within html language

The formatting of this table is causing issues with printing <tr height="95%"> <td width="100%"> <div id="placeSchedule"> <table bgcolor="red" width="100%" height="100%" border="1"> <tr> < ...

Is there a risk of overloading the server and browser by making constant AJAX calls at regular intervals?

I am in the process of creating a website that requires notifications. I want to use AJAX to continuously check for updates in my database where notifications are stored at regular intervals. My concern is, with multiple users all accessing the AJAX call ...

Loop through items in a list using Angular.js and display each item within an <

I am facing an issue where the model returned from the server contains html tags instead of plain text, such as b tag or i tag. When I use ng-repeat to create a list based on this model, the html is displayed as pure text. Is there a filter or directive av ...

Performing multiple AJAX calls from JavaScript

for(var y=0 ; y<=23 ; y++) { AjaxRequest99 = null; AjaxRequest99 = getXmlHttpRequestObject(); // method to initiate the request if(AjaxRequest99.readyState == 4 || AjaxRequest99.readyState == 0) { AjaxRequest99.open("GET", "aja ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

Issue: When calling setState(...), you must provide either an object containing the state variables to update or a function that will return an object with the updated

Encountering an error in the else section with this.state.incorrect + 1 and this.state.correct + 1 I've come across a similar issue that wasn't resolved by visiting this link: React Native: setState(...): takes an object of state variables to up ...

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

The React Router Dom V6 triggers loaders as soon as the router is initialized

I'm currently working on implementing routing into my application using react-router-dom V6, specifically utilizing the new createBrowserRouter function and RouterProvider component. The issue I'm facing is that when attempting to integrate a lo ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...

Tips for displaying real-time error notifications from server-side validation using AJAX

Seeking a way to display inline error messages from my Symfony2 Backend without refreshing the page. I considered replacing the current form in the HTML with the validated form containing the error messages returned by the backend through AJAX. However, ...

What is the process for retrieving the AJAX response text?

When it comes to my AJAX development, I rely on prototype and utilize the following code: somefunction: function(){ var result = ""; myAjax = new Ajax.Request(postUrl, { method: 'post', postBody: postData, content ...

Nesting conditions within partials using Handlebars

Hey there! I'm having an issue with my page layout, here's what it looks like: --- title: Coffee replace: true --- {{> products-list-style}} So, my partial "products-list-style" is like this: {{#if ../replace}}Replace{{else}}Add to Cart{{/i ...

Vue routing stops working when there is no hash in the URL (no designated input file)

I am facing the need to operate Vue router in its default mode, known as hash mode, and unable to use it in history mode. In this mode, all my dynamic routes have a leading hash, like http://myurl.com/#/highlights. However, removing that initial hash, such ...