How to use CSS Classes In Vue

In this approach we use CSS clases to bind background image, if you have styles for different background images then this approach helps in bind them dynamically.

Syntax:

<div :class="{ 'background-class-1': condition, 'background-class-2': !condition }"></div>

Example: The below example explains the use of the classes to bind the styles using VueJS.

HTML




<!DOCTYPE html>
 
<html>
<head>
    <title>
        Background Image binding in VueJS
    </title>
    <style>
        #app{
            text-align: center;
        }
 
        .backgroundBindClass{
            background-image:
url('https://media.w3wiki.org/wp-content/cdn-uploads/20220131222755/Vue.js-Tutorial.png');
            height: 300px;
            width: 800px;
            background-size: cover;
            background-repeat: no-repeat;
            margin: auto
        }
 
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <div id="app">
        <h1>
            w3wiki
        </h1>
        <div :class="{'backgroundBindClass': condition}">
            <h3>
                  Background Image binding using the CSS
                  Classes in VueJS.
              </h3>
            <h4>
                  This Background image is bounded using
                  the CSS Classes in VueJS.
              </h4>
 
        </div>
    </div>
 
    <!-- VueJS CDN Link -->
    <script src=
"https://cdn.jsdelivr.net/npm/vue@2">
    </script>
 
    <script>
        new Vue({
            el: '#app',
            data: {
                condition: true
            }
        })
    </script>
</body>
 
</html>


Output:



How to Bind the Background Image in VueJS ?

In VueJS, the background images can be set from different types of properties like data property, computed property, or directly from an image source. In this article, we will see the different approaches to bind the background image in VueJS as listed below:

Table of Content

  • Using Inline Style
  • Using CSS Classes

Similar Reads

Using Inline Style

In this approach, we directly bind the background image by specifying inline styles using the style attribute....

Using CSS Classes

...