Getting a Current CSS Value

Example

Let’s say you want to know the current color of a background that changes depending on the width of the screen.

#coloredBox {
	background-color:lemonChiffon;
}
@media only screen
and (max-width: 767px) {
	#coloredBox {
		background-color:aquaMarine;
	}
}
Hi

Change the width of this browser window and you’ll see the color change in the box to the right.

If you want to know what the current color is, you can use the following function:

function getStyle(elem, cssprop){
	//Cross-browser method for reading the current the value of a CSS property.
	if (elem.currentStyle) { //IE
		return elem.currentStyle[cssprop];
	} else if (document.defaultView && document.defaultView.getComputedStyle) { //standards method
		return document.defaultView.getComputedStyle(elem, "")[cssprop];
	} else { //try and get inline style
		return elem.style[cssprop];
	}
}

var currentColor = getStyle(document.getElementById('coloredBox'),'background-color');

If you are already using jQuery in your project, then an easy way to read the value of a CSS property is:

var currentColor = $('#coloredBox').css('background-color');