jQuery CSS Methods
The .css() method reads and changes the style of an element. It is the quick way when the value comes from your code.
Get a CSS property
<p id="text" style="color: red; font-size: 20px;">Hello</p>
console.log($('#text').css('color'));
console.log($('#text').css('font-size'));
rgb(255, 0, 0)
20px
Notice that the color is returned in the rgb() format, not as the word red which we wrote. Browsers return the computed value, so compare colors with care.
Set a CSS property
<p id="text">Hello</p>
$('#text').css('color', 'blue');
<p id="text" style="color: blue;">Hello</p>
Set many properties
$('#text').css({
'color': 'green',
'font-size': '18px',
'background-color': '#eee'
});
<p id="text" style="color: green; font-size: 18px; background-color: rgb(238, 238, 238);">Hello</p>
You can write the property names in the CSS way with a dash ('font-size') or in camelCase (fontSize). With an object, camelCase does not need quotes.
Relative values
<div id="box" style="width: 100px">Box</div>
$('#box').css('width', '+=50');
console.log($('#box').css('width'));
150px
Use a function
<p>A</p><p>B</p><p>C</p>
$('p').css('padding-left', function (index) {
return (index * 10) + 'px';
});
<p style="padding-left: 0px;">A</p>
<p style="padding-left: 10px;">B</p>
<p style="padding-left: 20px;">C</p>
Remove a style
<p id="text" style="color: red; font-weight: bold;">Hello</p>
$('#text').css('color', ''); // an empty string removes the inline style
<p id="text" style="font-weight: bold;">Hello</p>
width() and height() methods
These methods are used to get and set the size of an element, in numbers without the “px”.
| Method | Returns |
|---|---|
.width() / .height() | Size of the content only |
.innerWidth() / .innerHeight() | Content and padding |
.outerWidth() / .outerHeight() | Content, padding and border (and margin with true) |
console.log($('#box').width());
$('#box').width(300).height(150);
In a real browser these methods give the real size on the screen. They need a layout, so they return 0 in a test tool without a browser engine. We do not run them in our test environment.
css() vs classes
- Class: best for fixed designs. It is easy to change in your CSS file, and the HTML and JavaScript stay clean.
- css(): good for dynamic values, like the size from a slider or a position from a calculation.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |