Skip to content
Related Articles

Related Articles

Improve Article

Tailwind CSS Background Attachment

  • Last Updated : 14 Jul, 2021

In this article, we will learn how to attach background images using Tailwind CSS.

Approach:

You can easily attach background images using the background-attachment property in Tailwind CSS.  All the properties are covered in class form. It is the alternative to the CSS background-attachment property. It can be set to scroll or remain fixed. 

Background attachment classes:

  • bg-fixed: This class is used to fix the background image relative to the viewport.
  • bg-local: This class is used to scroll the background image with the container and the viewport.
  • bg-scroll: This class is used to scroll the background image with the viewport, but not with the container.

 



Syntax:

<div class="bg-fixed ...">
    ...
</div>

Example 1: The following example demonstrates fixing the background image relative to the viewport using the bg-fixed class. 

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link href=
"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"
        rel="stylesheet">
</head>
  
<body class="text-center">
    <h1 class="text-green-600 text-5xl font-bold">
        GeeksforGeeks
    </h1>
  
    <b>Tailwind CSS Background Attachment Class</b>
      
    <div class="mx-4  h-screen w-full">
        <div class="bg-fixed bg-contain overflow-auto 
            m-20 h-80 w-38" style="background-image:url(
            )">
        </div>
    </div>
</body>
  
</html>

Output:

bg-fixed

Example 2: The following example demonstrates fixing the background image with the container and the viewport using the bg-local property.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link href=
"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"
        rel="stylesheet">
</head>
  
<body>
  
    <div class="mx-4  flex items-center 
        justify-center h-screen w-full">
  
        <div class="bg-local bg-contain 
            overflow-auto m-20 h-80 w-38" 
            style="background-image:url(
  
            <div class="h-64 w-64"></div>
        </div>
    </div>
</body>
  
</html>

Output:

bg-local

Example 3: The following example demonstrates fixing the background image with the viewport, but not with the container using the bg-scroll property.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <link href=
"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"
        rel="stylesheet">
</head>
  
<body>
  
    <div class="mx-4  flex items-center 
        justify-center h-screen w-full">
  
        <div class="bg-scroll bg-contain 
            overflow-auto m-20 h-60 w-38" 
            style="background-image:url(
            )">
              
            <div class="h-64 w-64"></div>
        </div>
    </div>
</body>
  
</html>

Output:

bg-scroll




My Personal Notes arrow_drop_up
Recommended Articles
Page :