Home > front end >  Position body background image relative to child div
Position body background image relative to child div

Time:04-03

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>

CodePudding user response:

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

CodePudding user response:

If the image is going to be a background of <body> using CSS rather than trying to insert it onto the HTML page as an <img> then you could perhaps use 50% 50% to position it?

50% 50% will put the image exactly in the center though.

body{
  background: ( path-to-your-image ) 50% 50% no-repeat;
}

So you might want to try something like this to shift it over to the left a bit.

body{
  background: ( path-to-your-image ) 15% 50% no-repeat;
}

  • Related