Stats

215 Contributors: 14 Monday, January 16, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

CSS Manipulation

Syntax

  • .css( cssProperty ) // Get the rendered CSS property value
  • .css( [cssProperty , ...] ) // Get values from Array of cssProperties
  • .css( cssProperty, value ) // Set value
  • .css( {cssProperty:value, ...} ) // Set properties and values
  • .css( cssProperty, function ) // Expose the cssProperty to a callback function

Remarks

Rendered values

If a responsive unit is used (like "auto", "%", "vw" etc.), .css() will return the actual rendered value in px

.myElement{ width: 20%; }
var width = $(".myElement").css("width"); // "123px" 

Formatting properties and values

Properties can be defined using standard CSS formatting as String or using camelCase

"margin-bottom"
marginBottom

Values should be expressed in String. Numeric values are treated as px units internally by jQuery

.css(fontSize: "1em")
.css(fontSize: "16px")
.css(fontSize: 16)      // px will be used

As of jQuery 3 avoid using .show() and .hide()

According to this jQuery Blog post, due to overhead and performance issues, you should no longer be using .show() or .hide().

If you have elements in a stylesheet that are set to display: none, the .show() method will no longer override that. So the most important rule for moving to jQuery 3.0 is this: Don’t use a stylesheet to set the default of display: none and then try to use .show() – or any method that shows elements, such as .slideDown() and .fadeIn() – to make it visible. If you need an element to be hidden by default, the best way is to add a class name like “hidden” to the element and define that class to be display: none in a stylesheet. Then you can add or remove that class using jQuery’s .addClass() and .removeClass() methods to control visibility. Alternately, you can have a .ready() handler call .hide() on the elements before they are displayed on the page. Or, if you really must retain the stylesheet default, you can use .css("display", "block") (or the appropriate display value) to override the stylesheet.

Related Examples