Struggling with modifying background color in Vue.js?

My intention is to make the landing page background color orange, but I'm encountering an issue where all pages end up with the same color.

I attempted to use scoped on the landing page to target only that specific page, however, it resulted in the entire page losing its orange background.

The main objective here is to alter only the landing page.

I've already experimented with using HTML and Body instead of the ' * ', but those approaches didn't yield the desired outcome in this scenario either.

landingpage.vue:

<template>
    <div class="container">
        <div class=landing>
            <h1>Hello.</h1>
            <router-link to="/work">
                <button id="work" type="button">See my work</button>
            </router-link>
            <router-link to="/home">
                <button id="home" type="button">Go home</button>
            </router-link>
        </div>
    </div>
</template>

<script>
export default {
  name: 'Landing',
};
</script>

<style scoped>
* {
    background: orange;
}

h1 {
    margin-top: 100px;
    text-align: center;
    font-size: 80px;
    color: green;
}
#work {
    color: green;
    border: none;
    font-size: 25px;
    text-decoration: none;
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
#work:hover {
    color: white;
}
#home{
    color: green;
    border: none;
    font-size: 15px;
    text-decoration: none;
    margin: 0;
    position: absolute;
    top: 70%;
    left: 50%;
    -ms-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
#home:hover {
    color: white;
}
</style>

Answer №1

When using Vue Router in a Single Page Application (SPA), the <code>HTML
and body elements are outside of the application scope, meaning they do not re-render when transitioning from one page to another.

The first issue - SPA:

In a Single File Component, styles applied to the body and html tags will only take effect upon a page refresh (e.g., going from page-1 to page-2 and clicking on F5):

<!-- page_2 -->
<style>
   body{
    background: orange; /* does not apply when transitioning between pages */
   }
</style>

The second issue - "out of scoped":

The use of scoped in CSS limits its application to elements within the current component scope, excluding the body element.

Solution with Hello World concept:

A simple solution is to utilize Lifecycle Hooks to dynamically change the background color of the body tag. On created, set the background color to orange, and on destroyed, remove it:

<script>
export default {
  name: "orange-page",
  created: function () {
    document.body.style.backgroundColor = "orange";
  },
  destroyed: function () {
    document.body.style.backgroundColor = null;
  },
};
</script>

Creating a "min:100vh app":

An alternative approach is to add a wrapper element with a style of min:100vh inside your #app to cover the entire body/html area (body { margin: 0;} must be set):

Further reading: Changing Page Background Color for Each Route

Exploring more solutions:

Changing Body Styles in Vue Router

CSS best practice:

It is recommended to apply general styles to the body tag:

body{
   background: orange;
}

Avoid using the wildcard selector (*) as it selects all elements on the page:

Answer №2

Try this new approach:

html {
    background: orange;
}

or even better,

body {
    background: orange;
}

Answer №3

To add a dynamic binding to the class so it only shows on the landing page route, consider implementing this approach:

In your App.vue file or any higher-level component serving as the app shell, you can do something like this:

/* ==== in App.vue (or Landing Page parent Component) ==== */
<template>
  <div :class={orangeBackground: $route.path.includes('/landingPagePath')}>
     // other content here, such as the router view
     <router-view> </router-view>
  </div>   
</template>
<script>
</script>
<style>
.orangeBackground {
    background: orange;
}
</style>

The concept revolves around wrapping the DOM within the parent component and toggling the .orangeBackground class based on whether the user is on the landing page route.

Answer №4

Utilizing the latest composition API, your code will take on this form:

setup() {
  var color = "#343E3D";
  onMounted(() => {
    console.log("mounted!");
    document.body.style.backgroundColor = color;
  });
  onUnmounted(() => {
    console.log("unmounted!");
    document.body.style.backgroundColor = null;
  });
  return {};
},

By utilizing these two Lifecycle Hooks, you can dynamically alter the background when your component is loaded or unloaded. I encountered a similar issue where one page required a distinct background compared to the rest of the website.

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

What are the steps to integrate the extract text plugin with Vue component CSS?

After successfully adding the extract text plugin to extract sass and scss for vue components, I am now interested in learning how to incorporate the extract text plugin for regular css as well. ...

Switching between blog posts in a Vue application by clicking on a link from the sidebar labeled "Recent Updates."

Having an issue with my personal project, I created a BlogPost.vue file where I display the post that was previously clicked on from a Blog.vue page. In this BlogPost component, I showcase the title and content of the selected post, while also featuring a ...

Guide on incorporating a Python script into a website using DJango

I am new to Django and looking for guidance. My goal is to have users input text in an HTML textbox, then process that text using Python and display it on the website. Despite going through documentation and tutorials, I have not been successful in gettin ...

Ways to reverse engineer HTML, CSS, and JavaScript code into HTML format

Help needed! I am trying to edit the user interface but all the code is in one line and I can't figure out how to decompile it back to its original state. Can anyone offer assistance with this? <html lang="en"><head><meta char ...

Display specific content according to the hash in the URL

I have a website with a page (/categories.html) that contains around 50 p elements: <p id='BCI'>Blue_colored_items</p> <p id='RCI'>Red_colored_items</p> ... What I want is for the page to only display: Blue_co ...

Styling tooltips using only css - Dealing with overflow issues

What is the best way to effectively showcase these tooltips? When using overflow visible, the issue is resolved, but it causes other elements to spill out of the div. How can this be addressed? HTML: <div id="test"> <a title='Sample tooltip& ...

Troubleshooting issues with AJAX script and JSON formatted data

Here is my complete script: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/E ...

Deciphering the GWT compiler's results

Although I'm not a JavaScript developer, I'm currently delving into the process of converting Java code to JS using the GWT compiler in order to identify the root cause of memory growth in our extensive application. Every now and then, I come ac ...

The reason why JavaScript condenses two or more spaces into just one space

After encountering a problem with my HTML/JS/Angular script, I created a simple demo to illustrate the issue. Although I have found a solution, I still wanted to seek advice from experts. <body ng-app> <div ng-controller='abc'> ...

Dynamic div with height controlled by the content of the background image

I'm trying to figure out how to make a div with a background image of 100% width always maintain the aspect ratio of the image for its height. Is there a way to achieve this? In simpler terms, when I resize the page, I want the div to scale down whil ...

How can I reset the mousemove event in jQuery?

I need to create a mechanism where I can move a div by clicking on it, and then click again to stop the div in that position. However, encountering an issue when trying to move the div again as the mousemove event does not get activated. How can this be ...

Submitting an mvc partial view form to send data from the parent view

I am currently working on a MVC 5 App where I have a Parent View that includes a Partial View, allowing users to load images. Upon submitting, the Parent view calls a .Ajax function defined within it, which in turn calls a Method/Controller. My requireme ...

What steps should I take to develop an Outlook add-in that displays read receipts for action items in sent emails?

Currently, I am in the process of developing an add-in that will enable me to track email activity using a tool called lead-boxer (). With this add-in, I am able to retrieve detailed information about users who have opened my emails by sending them with an ...

Access control using Vue.js Cookies

Within my current project, we have both superusers and staff members. The specific task of deleting users is reserved for the superuser role only. This leads me to question whether it is plausible to delete a user by utilizing cookies? ...

Error in Angular Universal: KeyboardEvent is not defined

I have inserted the word "domino" into the server.ts file and updated the webpack.server.config.js as follows: module: { rules: [ { test: /\.(ts|js)$/, loader: 'regexp-replace-loader', options: { match: { pattern: '&bs ...

I believe this solution is functional, but it seems to undermine the intention of utilizing a framework

Having just started with vue and js, I recently put together a photo gallery. I'm looking to reduce the opacity of selected photos and then reset it when switching between photos. The current code works fine, but I believe there could be a better way ...

Failure to choose a value in AngularJS using the Chosen directive

I am currently developing a project with AngularJS and I need to display the selected value. To achieve this, I am utilizing the chosen filter available at: https://github.com/leocaseiro/angular-chosen Below is the code snippet that I have implemented: ...

Utilizing Jquery to automatically scroll to a specific div on page load by setting an

I am attempting to automatically scroll to the div specified in the URL. The URL may include one of 21 different IDs such as: url.com/test#lite1 url.com/test#lite2 url.com/test#lite3 This scrolling action should happen when the page loads (so that user ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...