Search code examples
javascriptcssgetcomputedstyle

getComputedStyle returns unexpected CSS values


I'm trying to access a CSS rule's value using getComputedStyle. The following is the value I'm trying to access:

background: linear-gradient(to right, red , yellow);

But when I test this I instead receive the following value:

rgba(0, 0, 0, 0) linear-gradient(to right, red, yellow) repeat scroll 0% 0% / auto padding-box border-box

Following is the code I'm using:

console.log(window.getComputedStyle(body, null).getPropertyValue("background"));

I wanted explanation as to why these additional values are being printed, why I'm not getting only the value written in my stylesheet, and how I would go about only getting that value.


Solution

  • As Chris G notes, background as a shorthand sets multiple longhand properties at once, including ones you don't specify. So the computed value of the background shorthand contains values for all the longhands that it applies, in addition to the gradient you did specify — these will all be set to their initial value since you didn't specify them but used the background shorthand. The browser still needs to compute these other values so it can render the layout, and assumes you might be interested in these other values so it hands them to you when you ask for the shorthand.

    If you're only interested in the gradient, get the value of the background-image property instead.