6

Most web browsers, by default, render pages as having a white background. However, this is to some extent user customizable, and some browsers are different. So, I want to find a way, either through CSS or JavaScript, to find out the background color of the page. The documentation on Mozilla's website suggests that document.bgColor can be used, and that its default value is white. It also suggests to not use it, since it's deprecated. But the docs seem to be in conflict with observed behavior: document.bgColor is an empty string if the page has no CSS to change it. The alternatives suggested don't work either: everything I tried gives me either an empty string or "transparent", which is clearly wrong: I can not see the desktop beneath my browser, hence it is not transparent. (Incidentally, IE11 actually behaves like Mozilla's documentation says that Firefox does. Go figure.)

I want to create an html list element (<ul>) whose background color matches the background color of the document. Is this possible? (I suppose you might be tempted to ask: if I want it to match the background, isn't "transparent" what I want? No. I want it to cover up some other element. Why? Because I'm making one of those auto-suggest thingies.)

Edit: 2 people have wisely suggested that I add an example so it becomes clear what on earth I'm talking about. Based on the answers I've been receiving, these 2 people are absolutely right. I've added a link to a fiddle in the comments of one of the answers, and now I'm adding it here:

https://jsfiddle.net/ftgu97fj/5/

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
Mark VY
  • 1,489
  • 16
  • 31
  • http://www.useallfive.com/thoughts/javascript-tool-detect-if-a-dom-element-is-truly-visible/ – Hitmands Sep 17 '16 at 05:41
  • this seems to be solving a different problem? – Mark VY Sep 17 '16 at 05:45
  • It does, but in that guys's code you can find the solution. Which IE version is the oldest you have to support? – connexo Sep 17 '16 at 05:48
  • this helps you to find elements that are in viewport, then, you need to pick up the element that (for you) is most important, finally, access to its `style.backgroundColor` property. – Hitmands Sep 17 '16 at 05:51
  • For the sake of this question let's say IE11. – Mark VY Sep 17 '16 at 05:51
  • I seem to have done a bad job explaining my question. My problem is that style.backgroundColor is giving me the wrong answer. – Mark VY Sep 17 '16 at 05:52
  • https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle should work all the way down to IE 9. – connexo Sep 17 '16 at 05:53
  • 2
    On an empty page in Chrome: `window.getComputedStyle(document.body)["background-color"] "rgba(0, 0, 0, 0)"` – Larkeith Sep 17 '16 at 06:00
  • _"My problem is that style.backgroundColor is giving me the wrong answer"_ Does the `` element have a `style` attribute? – guest271314 Sep 17 '16 at 06:01
  • 1
    @guest271314 the goal is to identify the background color for a page where it has not been set; that is, the default background color of the browser the client is using. – Larkeith Sep 17 '16 at 06:02
  • @MarkVY Will the `
      ` be a direct descendant of `` element
    – guest271314 Sep 17 '16 at 06:02
  • Instead of trying to cover up another element, why don't you set the (css) opacity to 0 and then to 1 when you want it to appear? – R. Schifini Sep 17 '16 at 06:03
  • @Larkeith Yes. OP was querying value `style` attribute of element at `style.backgroundColor ` – guest271314 Sep 17 '16 at 06:03
  • @The ul will be a child of a form element. And I've tried setting the opacity of the list to 1 and it has no effect, because the browser thinks the color is transparent so making it fully opaque is a no-op. – Mark VY Sep 17 '16 at 06:13
  • What do you mean by "the browser thinks the color is transparent"? Have you tried `form, form ul {background-color:inherit}`? Is the `` element `background-color` set to a value other than `transparent`? – guest271314 Sep 17 '16 at 06:14
  • 2
    People could write hypothetical answers to a hypothetical question all day long - it certainly keeps the electricity companies happy. As a better and more usual alternative however, you could simply include the markup you're using and turn this into a concrete problem. – enhzflep Sep 17 '16 at 06:40

6 Answers6

8

You could use CSS2 system colors - note that these are deprecated in CSS3 and appearance property is advised to use instead.

ul { background-color: Background; } /* this should be desktop background */

ul { background-color: Window; } /* this is browser background */

However, after 5+ years, the standards turned 180 degrees: the appearance was abandoned (except for none value) and system colors are back with different names, see Michael Alan's answer here.

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • woah, this is really neat – Mark VY Sep 17 '16 at 07:03
  • 1
    This is an excellent catch; you can even then use `window.getComputedStyle` to find out what the color is. Unfortunately, it seems to exhibit some very strange behaviour - In Firefox, it's black, whereas in Chrome on a blank page, it uses a dark purple instead of the default white (rgb(99, 99, 206)). Can be demonstrated by using `document.body.style.backgroundColor="background"` on `about:blank`. – Larkeith Sep 17 '16 at 07:29
  • 2
    After a bit more investigation, using `background-color: Window;` seems to get the "true" default background color. This can then be obtained with `window.getComputedStyle`. Example: `document.body.style.backgroundColor="Window"; alert(window.getComputedStyle(document.body)["background-color"]);` – Larkeith Sep 17 '16 at 07:32
  • @Larkeith `document.body.style.backgroundColor="Window";` first sets the `backgroundColor` property, yes? – guest271314 Sep 17 '16 at 07:39
  • 1
    @guest271314 Per the linked documentation, it sets it to the default background color of the window; it should never change the color from that of a blank page. – Larkeith Sep 17 '16 at 07:41
  • @Larkeith Yes. Not certain what OP is trying to achieve? Set the color of an element to the default color of `window` or `document.body`, see http://stackoverflow.com/questions/39543197/get-the-documents-background-color/39543405?noredirect=1#comment66401184_39543405 ? Where `document.body` or other parent element of `
      ` could have a `background` or `background-color` other than `window` default color. Perhaps if you believe that you have interpreted OP correctly you could update Question from _"Get the document's background color"_ which implies the `document` itself has a background color
    – guest271314 Sep 17 '16 at 07:48
  • 1
    @guest271314 I was under the impression from "if the page has no CSS to change it" and "by default" that OP is attempting to get the background of an unstyled html page (or at least where the background is not set). It is certainly fairly unclear; I would rather let OP edit it, but if he doesn't in a while I will do so. – Larkeith Sep 17 '16 at 07:56
  • @Larkeith is exactly right: that's precisely what I meant. Larkeith: thank you for having psychic powers. – Mark VY Sep 17 '16 at 07:58
  • @Larkeith _""if the page has no CSS to change it""_ If OP is creating the `.html` document, the background color of `` or `` elements can be set to any valid color OP selects. Set `
      ` background color to `html` or `body` background color, then select contrasting color for text. Why query default browser styles when the colors can be set manually, and specifically, to achieve expected result?
    – guest271314 Sep 17 '16 at 08:02
  • 1
    @guest271314 I don't know why OP wants to use the default color of the browser, and would agree that manually setting the colors would generally be a better idea, as well as more reliable and cross-compatible. But, that advice doesn't answer OP's specific question. – Larkeith Sep 17 '16 at 08:23
  • @Larkeith You appear to gather OP's specific Question to a greater extent than this viewer of actual Question; and further description of what expected result is at [comment](http://stackoverflow.com/questions/39543197/get-the-documents-background-color/39543405?noredirect=1#comment66401698_39543405). What is specific Question? From perspective here, it is unclear what OP is seeking. Either set the colors, or use `inherit`, `initial` or other `css` keyword. Not certain there is an in-between solution? – guest271314 Sep 17 '16 at 08:25
  • 1
    @guest271314 OP would like to have a page that uses the client browser's default background color (which is usually white, but not always). On that page, there is a section which has a set color. He would like to add a subsection to the colored section that has the same color as the main page, "cutting a hole" in the colored section; this can't be set to a specific color, as the main page's color might vary from browser to browser. – Larkeith Sep 17 '16 at 08:29
  • @Larkeith What if user does not prefer window default colors? Then user has to attempt to further adjust the colors. Provide a method for user to set their own colors. Then style the specific elements based on user selection. Or, use approach that you suggested at http://stackoverflow.com/questions/39543197/get-the-documents-background-color/39543405?noredirect=1#comment66401072_39543711, which should resolve Question? – guest271314 Sep 17 '16 at 08:32
  • @guest271314 Giving users an option to choose between styles is probably the best way of going about this, if it's a necessity to allow multiple styles. It should be noted it can decrease usability though, depending on the application. Personally, I would probably just set the background to white, but I'm sure there are rare cases where the background has to be variable. – Larkeith Sep 17 '16 at 08:51
4

EDIT: Jan Turoň has found a method of doing this using CSS2 System Colors; Please defer to his answer. Note that the system colors are deprecated and that window is the default background color.

Based on the answer in this post regarding background color of highlighted text, it seems that this is likely not possible; the relevant question is also a browser-specific choice of a very similar nature:

Kaiido:

I would say that you can't.

Both getComputedStyle(yourElement, '::selection').backgroundColor and getComputedStyle(yourElement, '::-moz-selection').backgroundColor will return transparent as default value and browser won't override os's default. (Worth to be mentioned that if you set it to transparent, default os' value will be overriden).

I don't think browsers have access to os default preferences, and if they do, they probably won't let any website access it it so easily.

This question suggests using a canvas element to sample the pixel color, but this unfortunately does not seem to work; in Chrome, it will return 0,0,0,0 for the color of an unset pixel. It gives a potential solution using chrome.tabs, but this is only available to chrome extensions.

The only possibility I can think of would be to use something like HTML2Canvas to "screenshot" the page and sample an empty pixel there, but there is no guarantee this library will operate properly for an unset background.

Community
  • 1
  • 1
Larkeith
  • 434
  • 2
  • 9
3

Nowadays, with access to the system colours and other user preferences, we can simply do this:

    ul { background-color: Canvas }

See: CSS Color Module § System Colors

Michael Allan
  • 3,731
  • 23
  • 31
1

If <ul> element is a direct descendant of <body> element you can use css inherit keyword

  ul {
    background-color: inherit;
  }
guest271314
  • 1
  • 15
  • 104
  • 177
  • 2
    Doesn't work. Since the browser is busy pretending that the body is transparent, the list inherits this, and is also transparent. – Mark VY Sep 17 '16 at 06:09
  • 1
    _"Doesn't work. Since the browser is busy pretending that the body is transparent"_ Can you create a jsfiddle http://jsfiddle.net to demonstrate? Is the `` element `background-color` set to `transparent`? – guest271314 Sep 17 '16 at 06:10
  • @MarkVY Still not valid `html`. Missing closing ``, `` `` tags, quotes at `` element `type` attribute value. What does jsfiddle demonstrate? – guest271314 Sep 17 '16 at 07:05
  • The point is that the list is not legible because it's right on top of the submit button. Fixed: https://jsfiddle.net/ftgu97fj/5/ – Mark VY Sep 17 '16 at 07:07
  • _"The point is that the list is not legible because it's right on top of the submit button."_ That is due to `position:absolute`. The `background-color` of `
      ` element is inherited from `body` using approach at Answer https://jsfiddle.net/ftgu97fj/10/
    – guest271314 Sep 17 '16 at 07:12
  • Yes! I want it to be absolute! And I want it to obscure the submit button, so that it remains legible. – Mark VY Sep 17 '16 at 07:15
  • @MarkVY _"Yes! I want it to be absolute! And I want it to obscure the submit button, so that it remains legible."_ That is not related to actual Question _"Get the document's background color"_. Using `inherit` inherits the value of the parent element for that specific `css` property. – guest271314 Sep 17 '16 at 07:17
  • The question title is phrased poorly I admit, but the question text itself spends an entire paragraph trying to explain what I want. Not well enough it seems. The fact is: the document has some background color; probably white. How do I get the browser to tell me what it is? – Mark VY Sep 17 '16 at 07:20
  • _"The fact is: the document has some background color; "_ The `document` itself does not have a background color. `document.body` `background-color` is not "probably white". How did you form this conclusion? – guest271314 Sep 17 '16 at 07:22
  • You're right: `background-color` is not "probably white". But I don't care about `background-color`. I care about the actual color of the actual pixels on the actual browser's actual screen. They are probably white. How can I get the browser to tell me so? – Mark VY Sep 17 '16 at 07:26
  • _"They are probably white"_ The color of the screen is not "probably white". Again, how did you form this conclusion? _"How can I get the browser to tell me so? "_ You cannot if the `background-color` is not actually set to `white` or `#ffffff`. _"I care about the actual color of the actual pixels on the actual browser's actual screen."_ At which element? – guest271314 Sep 17 '16 at 07:27
  • Let's say the list element. – Mark VY Sep 17 '16 at 07:32
  • The return value of `getComputedStyle` for `
      ` element is `rgba(0, 0, 0, 0)`. See `console` at https://jsfiddle.net/ftgu97fj/10/
    – guest271314 Sep 17 '16 at 07:34
  • yes, I know; that's what I'm whining about. It is the wrong answer. At least, it is not the answer to the question I'm trying to ask, The browser window is not literally transparent (else I could see my desktop). I want to know its actual color. Can this be done? – Mark VY Sep 17 '16 at 07:40
  • Browser window is different from `document`. Perhaps consider updating actual Question with this description of requirement? Also, this does not take into account styles set at `html` or `body` elements – guest271314 Sep 17 '16 at 07:41
  • If you would care to suggest a better phrasing, I would be glad to do so. – Mark VY Sep 17 '16 at 07:43
  • Still not certain exactly what you are trying to achieve? Though "Get the document's background color" does not appear to be what you are trying to retrieve? – guest271314 Sep 17 '16 at 07:44
  • Look at the Wikipedia home page. They have a neat autocomplete widget. I want one too. One of the pieces I need is that the dynamically generated list of suggestions is legible. Thus they should not be transparent; instead they should cover whatever is beneath them. Thus they need a background color. Which background color? Preferably whatever the default is that the browser is already using. Am I making any sense? – Mark VY Sep 17 '16 at 07:52
  • @MarkVY _"Preferably whatever the default is that the browser is already using."_ The default background color of `window` could be different from the parent element background color. You could simply set the background color of the specific element to the parent elements' background color, or set the background to a color you select with contrasting color for text. – guest271314 Sep 17 '16 at 07:56
  • "You could simply set the background color of the specific element to the parent elements' background color". I would LOVE to do that. I can't figure out how to do this without risking accidentally overriding the defaults. Can you show me? – Mark VY Sep 17 '16 at 08:04
  • _"I can't figure out how to do this without risking accidentally overriding the defaults."_ What do you mean by "overriding the defaults". You are the author of the document. You set the defaults. Select the colors you would like to render at both `` and `
      ` elements, and `
        ` parent element; or any other elements which you choose to include within the `.html` document which you create. Note, it could also be that this user simply has not yet determined what issue you are trying to solve? @Larkeith appears to have a firmer grasp on what you are trying to accomplish, than here.
    – guest271314 Sep 17 '16 at 08:06
  • Yes, I am the author of the document. But I don't want to explicitly specify every color. Even without any CSS, the browser would make some choice as to colors. I want to keep those choices. If the user's browser normally has a black background, I want my document to also have one. If the user normally has a pink background, so should mine. – Mark VY Sep 17 '16 at 08:12
  • _"If the user's browser normally has a black background, I want my document to also have one. If the user normally has a pink background, so should mine"_ If you do not want to specify colors, you can use `inherit` or [`initial`](https://developer.mozilla.org/en-US/docs/Web/CSS/initial) keywords, as suggested at Answer. Though your [comment](http://stackoverflow.com/questions/39543197/get-the-documents-background-color/39543405?noredirect=1#comment66401371_39543405) suggest that you in fact do want to specify rendered colors at specifc elements ? – guest271314 Sep 17 '16 at 08:15
  • That ends up making the list transparent, which makes it illegible, which is bad. – Mark VY Sep 17 '16 at 08:17
  • Then you do want to specify colors, to satisfy your own view of what is "bad"? If this is correct, you can resolve the Question yourself by setting the colors which you prefer, instead or querying or relying on "default" `window` or other colors set at user-agent stylesheet. – guest271314 Sep 17 '16 at 08:18
  • Transparent is bad. Transparent is not a real color. I would very much like to use the user-agent style sheet. Or something similar. – Mark VY Sep 17 '16 at 08:30
  • Then you could load a document at each browser, inspect the user-agent style sheet, perform feature detection to check browser type, then apply the default user-agent styles previously reviewed. Or, allow user to select color which they prefer. _"Transparent is not a real color"_ The light from the sun viewed by human eye does not appear to contain multiple colors, or be a single distinctive color itself; appearing transparent; though the light from the sun does contain multiple colors. – guest271314 Sep 17 '16 at 08:36
  • "... inspect style sheet ..." yikes! Is that really the easiest way to go? (re: transparent: pixels don't work with rgba; they only work with rgb; that's all I meant.) – Mark VY Sep 17 '16 at 08:44
1

Since comments are getting way too long on OPs post, here's what I'd suggest you try:

window.getComputedStyle(document.body)['backgroundColor'])

The usecase of your autosuggest displaying correctly on pages where no background-color has been set (such as empty page) should be covered by setting white as the default background color for your ul. It becomes alot more problematic if you want to take possible background-images into account as well.

Please also be aware that html can have a background-color as well, and body may be limited in size to not cover the whole viewport. See this pen:

http://codepen.io/connexo/pen/jrAxAZ

This also illustrates that your expectation to see your desktop behind your browser if the body were truly tranparent is wrong.

connexo
  • 53,704
  • 14
  • 91
  • 128
  • You misunderstood my usecase. I fully control the html on the page. I have no intention to use background images. But I do want to respect the browser defaults. If the user's browser has, say, black as the default background color, I don't want to override that, I want to respect it. – Mark VY Sep 17 '16 at 06:50
-1

This will definitely solve the problem! check how the js function works

function getBackground(jqueryElement) {
    // Is current element's background color set?
    var color = jqueryElement.css("background-color");
    
    if (color !== 'rgba(0, 0, 0, 0)') {
        // if so then return that color
        return color;
    }

    // if not: are you at the body element?
    if (jqueryElement.is("body")) {
        // return known 'false' value
        return false;
    } else {
        // call getBackground with parent item
        return getBackground(jqueryElement.parent());
    }
}

$(function() {
    alert(getBackground($("#target")));
    document.getElementById("ul").style.backgroundColor = getBackground($("#target"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<ul id= "ul" style="background-color: red">
    <p id="target">I'd like to know that the background-color here is red</p>
</ul>

i kept the prompt for your better understanding

Md Sifatul Islam
  • 846
  • 10
  • 28