Search code examples
cssbackground-imagebootstrap-5

Position body background image relative to child div


I need to position the background image of <body> relative to one of the child <div>s.

<body> 
    <div>content</div>       <-- place background image of body relative to this div
    <div>other content</div>
</body>

Placing body's background image relative to child element with content

The background image's size is bigger that the viewport and its top left corner shall be placed outside of the viewport.

My unsuccessful approach

My approach was to add the image as <img> with negative z-index and position: absolute but this approach adds horizontal scrollbars due to the image size

<body>
    <div style="position: relative">
        <img 
            src="..." 
            style="position: absolute; top: -100px; left: -400px; width: 800px; height: 600px; z-index: -1;" 
        />
        <div>content</div>
    </div>
</body>

Solution

  • You can fix your approach by using overflow-x:hidden; on the overflowed element or try position absolute with display inline