Using the ampersand symbol '&' in Sass to target the body tag with a particular class applied

Demo: https://codepen.io/moradxd/pen/WJpPyQ

Consider this sample HTML code:

<body class="boxed">
  <div class="text-white">
    <a href="#" class="btn-featured">Button</a>
  </div>
</dody>

I am implementing the following SASS code:

.boxed {
  // issue with using "Ampersand"
  body& {

  }
}

However, this leads to a compilation error which states:

https://i.sstatic.net/X8F0J.png

Even though I desire the output to be like this:

// Desired output
body.boxed {

}

I am aware that I can achieve the desired result by using the following syntax:

// Alternate solution
body {
  &.boxed {

  }
}

However, I prefer to separate the code for the .boxed class from the CSS code inside the body for organizational purposes.

So, why is this not permitted when a similar code structure for an element and its parent works perfectly fine like in the following example:

// Although this similar code for element and 
// its parent is effective
.btn-featured {
  .text-white & {
    font-size: 30px;
  }
}

I am genuinely curious to understand why this specific syntax is not allowed!

Answer №2

To make it work as intended, you should switch the order of your selectors like you mentioned.

body {
  &.boxed {
    background: red;
  }
}

The problem arises because the ampersand links the previous selector with the current one. For example, with this code:

.boxed {
  body & {
    background: red;
  }
}

It is attempting to add 'nothing' to the body tag within an element that has the class boxed. The correct approach is to follow the structure you initially described.

For more information, you can refer to the parent selector documentation.

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

Experience the ultimate Safari/iOS responsive design for seamless browsing on all

I am experiencing an issue with my website. In my "toggle device" toolbar, I selected the responsive option for iPhone 7 Plus, Galaxy 8, and others. While my website looks good on some devices, it does not function as desired when opened on an iPhone (7+/ ...

Turning my dual button navigation into tabs to display distinct HTML pages beneath a designated header

body{ background:url(background.jpg); background-size: cover; } h1{ font-family: 'Dancing Script', cursive; font-size: 5em; color: white; text-align: center; margin-top: 25px; margin-bottom: 20px; } h2{ font-size: 18px; color: white; text-align ...

The image filter plugin is functioning properly in one project, however, it is not working in

After successfully using a plugin from w3schools to filter elements in one project, I encountered an issue when attempting to implement it in another project. Here is the link to the problematic code pen: https://codepen.io/zakero/pen/mZYBPz If anyone ca ...

Move your cursor over one container to see the impact on another

My goal is to create a hover effect on a box that triggers another div with easing effects. Below, you'll see that the .images{} class has a 0s infinite scroll initially, but when the .box:hover > .images{} selector is activated, it changes to a 10 ...

How can you create a table cell that is only partially editable while still allowing inline JavaScript functions to work?

Just a few days back, I posted a question similar to this one and received an incredibly helpful response. However, my attempt at creating a table calculator has hit a snag. Each table row in a particular column already has an assigned `id` to transform t ...

Presentation Slider (HTML, CSS, JavaScript)

Embarking on my journey of creating webpages, I am eager to replicate the Windows 10 start UI and its browser animations. However, my lack of JavaScript knowledge presents a challenge. Any help in reviewing my code for potential issues would be greatly app ...

Dim the entire website

I am attempting to apply a grey overlay across my entire site when a file is dragged in for upload. The drag event and activation of the grey overlay are functioning correctly, but there are specific areas where it does not work as intended. There seems t ...

The CSS root variable is failing to have an impact on the HTML element's value

I'm in the process of changing the text color on home.html. I've defined the color property in a :root variable, but for some reason, it's not appearing correctly on the HTML page. Take a look at my code: home.scss :root { --prim-headclr : ...

Is it possible to set a unique identifier in Vue.js that persists even after the page is reloaded?

Currently, I'm working on a small project diving into Vue js - a Habittracker. Unfortunately, there is a bug in my code. When the page is reloaded and new habits are added, the function that should change the background doesn't work as expected. ...

Choose tag using position in a sequence

I am working on updating the label text "E-mail" to say "User Name" in this HTML markup. The only tool I have access to for this task is jQuery. <div class="foo" style="border:1px solid #444"> <span class="field-with-fancyplaceholde ...

The inclusion of individual CSS files in a TypeScript React project does not have any effect

My issue involves creating a new react project with typescript and adding a custom component with a separate CSS file for styling. The folder structure is as follows: https://i.sstatic.net/UNtEP.png In the Header.css file, I have defined a class: .mainHe ...

Issue with Chrome's webkit causing images to display incorrectly in slideshow

After researching the issue with webkit browsers and images, I came across a problem that I haven't been able to find a solution for yet. I developed a slideshow using jQuery that arranges images in a row and uses a mask element (with overflow: hidde ...

Limiting the use of CSS selectors to a single class without the need to include the class name multiple

I am trying to find a solution to avoid repeating the same class name multiple times in CSS. For instance, if I have: .class1 div { color: red } .class1 h2 { color: blue } .class1 p { color: yellow } Is there a way to consolidate these three rules under ...

What methods can I use to prevent floated child divs from wrapping?

I'm currently working on creating a carousel-like feature where users can select radio buttons within various div elements. The concept involves having approximately 20 divs, each 150px wide, containing radio buttons. I want to prevent these 20 divs f ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Adjust top position dynamically during resizing

When resizing the window, I am facing an issue with the image going outside of the box. I believe adjusting the position top of the image based on the box height might help in fitting the image properly within the box. $(window).resize(function() { va ...

CSS - Problem with background image appearing stretched on Samsung mobile devices

Is the Samsung default "Internet Browser" based on another build? It seems to have trouble displaying stretched background images correctly, unlike desktop browsers or Chrome for mobile. Here is the CSS and HTML I am using: #bk_img { height:100%; ...

Ensuring the width of a div matches the adjacent containers

I need assistance in creating a form that adjusts its width based on the form fields. The form contains both explanatory text and input fields, each enclosed in a div with inline-block set. The outer div (also using inline-block) should not expand beyond ...

Display a single item using Jquery when clicking on an element with the same class

I'm relatively new to JQuery/Javascript scripting and I'm having some difficulty. How can I display one item with the same class without affecting the other items? Here is my code: $(function() { $('.embedContainer > .myPosterImage& ...

Surprising margin discrepancy of 10px found while utilizing float property in CSS

Encountered an issue with the CSS property "float". There is a 10px margin at the top of the page. How can this be fixed? I tried adding an empty div to the parent div with id="background1", but it did not work. I also found this article https://css-trick ...