bygrace
bygrace

Reputation: 5988

display: none on body tag in chrome does not hide background

I have a site where I set the background image and color of the body tag via CSS. I hide it with the inline style display: none; so that optimizely has time to run and do any customizations without causing a flicker. This has worked till recently when the flicker came back but we haven't changed anything that seems related. I was debugging it and saw that in Chrome (Version 45.0.2454.101 (64-bit)) the background image and color are still displayed even though the body is display: none;. In firefox, safari, and IE11 the background is not displayed.

Here is some code to illustrate the issue:

<html>
   <head>
      <style>.background { background-color: red; }</style>
   </head>
   <body class="background" style="display: none;"></body>
</html>

I googled but couldn't figure out why. Any ideas?

To be clear the question is about why this happens on the body tag. I am open to alternate ways to hide the background image but wont consider them the answer.

Upvotes: 3

Views: 8877

Answers (1)

Jacob
Jacob

Reputation: 2154

Per the W3 CSS2 spec,

For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. User agents should observe the following precedence rules to fill in the background: if the value of the 'background' property for the HTML element is different from 'transparent' then use it, else use the value of the 'background' property for the BODY element. If the resulting value is 'transparent', the rendering is undefined.

According to this, if you set a background-color or background-image on the body, but don't set a background-color other than transparent on the html, then the html will use the body's background. So when you hide the body, the html will still be using it's background.

DEMO

var hideButton = $('#hide-body');
var toggleBGButton = $('#toggle-html-bg');

hideButton.on('click', function() {$('body').hide()} );
toggleBGButton.on('click', function() {$('html').toggleClass('bg')} );
html {
  background-color: transparent;
}

html.bg {
  background-color: orange;
}

body {
  background-image: url("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png");
  background-color: blue;
}

body.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="hide-body">Hide body</button>
<button id="toggle-html-bg">Toggle &lt;html&gt; background-color</button>

Upvotes: 7

Related Questions