Understanding the perplexing background-image behavior in the body element within CSS

I found myself puzzled by the background-image :

  1. background-image in div element

    When the background-image is applied to a div, the image appears inside the div.

  2. background-image in body element

    When the background-image is set on the body, the image shows outside of the body element.

Could someone shed some light on this?

This is what I got as a result https://i.sstatic.net/2rPHn.png

My code:

  body{
            height: 300px;
            width: 300px;
            position: absolute;
            top: 20%;
            left: 20%;
            border: 2px solid black;
            background-image: url('./alert.png');
            background-repeat: no-repeat;
 }
div{
             border:2px solid red;
             width:100px;
             height:100px;
             border: 2px solid red;
             background-image: url('./alert.png');
             background-repeat: no-repeat;
             position: absolute;
             top: 10%;
             left: 10%
 }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>test</title>
</head>
  
<body>
    <div>
    </div>
</body>

</html>

Answer №1

According to the guidelines (highlighted by me):

The root element's background extends throughout the canvas, covering it entirely and positioned at the same point as if it were painted only for the root element itself. The root element does not repaint this background.

However, it is recommended that authors set the background for the BODY element in HTML documents rather than the HTML element. When the root element of a document is an HTML "HTML" element or an XHTML "html" element with 'transparent' background-color and 'none' background-image computed values, user agents must then use the background properties from the first HTML "BODY" element or XHTML "body" element child when painting backgrounds on the canvas instead of painting a background for that child element. These backgrounds should also be anchored at the same point as they would be if they were originally painted for the root element only.

Answer №2

It's a bit unclear why this happens, but it seems like the <body> tag behaves differently because it acts as the root element of the page and typically wraps everything else. The background image or color of a <body> element is always positioned at the top left corner by default. To change this position, you would need to use the CSS property background-position, although this won't work with colors. One workaround is to set a background color for the <html> tag, but it's more of a temporary fix than a permanent solution. Personally, I prefer setting the margin and padding of the <body> tag to 0 and creating additional spacing using a <div> wrapper within the <body>. Below are two examples illustrating how to use background-position and how to create a fake "margin" for a background color using the <html> tag. By the way, could you explain why the body in your code snippet is positioned absolutely? I'm curious if there's a specific reason for this.

Adjusted Background for the Body

body {
  background: url('http://via.placeholder.com/350x150');
  background-position: 20px 50px;
  background-repeat: no-repeat;
  height: 200px;
  border: 1px solid;
}

Faux "Margin" Using the <html> Tag

html {
  background-color: #fff;
}

body {
  margin: 50px;
  background-color: #00ff00;
  height: 200px;
  border: 1px solid;
}

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

Revamping Footer Text

Hey there, I'm feeling a bit inexperienced with this question, so after struggling on my own for a while I decided to turn to stackoverflow for help. So, I have a website located at , and at the very bottom of the page there's some copyright inf ...

Ways to verify if a particular value is included in a list

I am faced with a situation where I need to display different content in HTML based on the presence of a specific value ("sign_change_global") in a JSON loaded from a server. I believe this issue can be resolved within HTML only, but I also wonder if there ...

CSS exclusive - achieving a horizontal scrolling list with all list items in a single row

I am working with a div that has a fixed width. Inside this div, there is an unordered list (ul) containing a random number of list items (li) with varying widths. My project utilizes the Bootstrap framework. Below is an example of the code structure: & ...

Containers with the ability to adjust based on screen

As I incorporate Bootstrap 4 into my project, I have come across the need for a more specialized solution specifically for search results. While exploring options, I stumbled upon an interesting project that allows the use of responsive containers tailored ...

Having trouble displaying json data in an HTML file with d3.js

I am having trouble loading data from a json file into an HTML file and using D3 to visualize it. Even though the file loads correctly and is verified with a 200 status, the contents are interpreted as null. Below are the contents of the json file: [{"to ...

Adding information into multiple tables from a single table

I am looking to streamline the process of displaying tables with identical entries on multiple HTML pages. Is there a way to create the table in one place and then call it into other pages? Could it be done like this: <table id="table1"> <th ...

Tips for incorporating transitions into CSS styling

After successfully adding a picture over an element when hovering over it, I decided to include a transition: 0.2s; property but unfortunately the transition effect is not working as expected. Why is this happening? My intention is for the picture to smoot ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Having trouble with the $push operator in Mongo DB?

I am facing an issue while attempting to store data in an array within an object in a Mongo model by utilizing the req.params method. Unfortunately, I encounter the following error: MongoError: cannot use the part (friends of friends.username) to traverse ...

jQuery append allows for the addition of multiple items simultaneously

I need assistance with automatically creating a div when clicking on a button. I'm encountering an issue where each click increments the display of the div. Can you provide some guidance on how to resolve this problem? ...

Ensure consistent switching of flexbox directional layout

I'm attempting to create a unique layout using only css3. My challenge is to achieve this without explicitly setting sizes, allowing the layout to flow freely. I am utilizing flexbox in my css for this purpose. After an automatic wrap, I want the layo ...

The Bootstrap grid feature is malfunctioning on both Codeply and devtools. The dimensions of the <div class="col-lg-3 col-md-4 col-sm-6"> element remain constant despite attempts to adjust them

After experimenting with the viewport meta tag and enclosing it in a div class="container", I found that the issue persists on Codeply and Chrome DevTools. However, when I adjust my browser size, the problem seems to disappear. I also tried using various v ...

Switch the 360-degree images by clicking a button using Panolen.js

As a beginner in the world of html, css, and javascript, I am trying to create a webpage that displays 360 panorama images. My goal is to have the image change when a button is clicked - for example, clicking on button 1 will display image1, while clicking ...

Implement a trigger to activate toggling functionality

<span id="test">​click</span>​​​​​​​​​​​​​​ $('#test').toggle(function() { alert('true'); }, function() { alert('false'); }); $('#test').trigger('click') ...

Show a div depending on user input

For those with more programming experience than myself, I have a simple question. In Rails, using coffescript, I want to show additional content based on a user's selection. Essentially, if they click on a checkbox, it should reveal an extra field for ...

Is there a way to align the arrow on the pills to the right center of the lengthy text?

I am struggling to align a pill on the right side of a header with long text using CSS. I need the pill to be centered at the right area with multiple lines of text. Can someone guide me on how to achieve this? Any assistance is appreciated. .c-cta-box- ...

Arrange the icons in multiple rows to ensure an equal distribution of icons on each row

There are 12 image icons displayed in a row within div elements using display: inline-block. However, when the browser window is resized, I would like the icons to be arranged on two or more rows so that each row contains an equal number of icons. ...

Inability to display text in IFrame print on Google Chrome

There is a perplexing issue with an iframe embedded within an HTML document. Despite the meticulous code structure, attempting to print the iframe in Google Chrome results in only a faint dotted line being visible on the final printout while Firefox handle ...

Placing a CSS image with absolute positioning on top of a responsive image

Is there a way to keep the balloon image position fixed in relation to the grid image when resizing it? The balloons Balloon1 and B2 are technically within grid 5 and 7, but if you resize the grid left or right, the balloons will go off-center. Do I requ ...

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...