Lesson 5 of 12

jQuery CSS and Classes

Showing an active tab, marking a form field as invalid, switching to dark mode – all of these are “change the look of an element” tasks. jQuery gives you two tools: class methods, which switch CSS classes on and off, and the .css() method, which reads or writes individual style properties. Knowing when to use classes and when to use jQuery CSS methods keeps your code tidy.

Prefer classes over inline styles

Put the design in your stylesheet as a class, and use jQuery only to add or remove that class. This keeps all the visual decisions in CSS, where a designer can change them without touching JavaScript, and it lets you use transitions, media queries and dark mode rules. It is the same advice as classList in plain JavaScript.

jQueryWhat it doesPlain JavaScript
.addClass('active')Adds one or more classesclassList.add('active')
.removeClass('active')Removes one or more classesclassList.remove('active')
.toggleClass('active')Adds the class if missing, removes it if presentclassList.toggle('active')
.toggleClass('active', isOn)Adds when isOn is true, removes when falseclassList.toggle('active', isOn)
.hasClass('active')True if any matched element has the classclassList.contains('active')

You can pass several classes separated by spaces, such as .addClass('card shadow'), or an array of class names. Like all setters, these methods work on every matched element and return the jQuery object for chaining.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Tabs with addClass and removeClass</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
    .tabs button { padding: 6px 14px; border: 1px solid #999; background: #f4f4f4; cursor: pointer; }
    .tabs button.active { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
    .panel { display: none; padding: 12px; border: 1px solid #ccc; margin-top: 8px; }
    .panel.show { display: block; }
  </style>
</head>
<body>
  <div class="tabs">
    <button type="button" data-tab="veg" class="active">Veg</button>
    <button type="button" data-tab="nonveg">Non-veg</button>
    <button type="button" data-tab="sweets">Sweets</button>
  </div>
  <div class="panel show" id="veg">Sambar rice, avial, curd rice</div>
  <div class="panel" id="nonveg">Chettinad chicken, fish fry</div>
  <div class="panel" id="sweets">Payasam, Mysore pak</div>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
$('.tabs').on('click', 'button', (event) => {
  const $btn = $(event.currentTarget);
  const id = $btn.attr('data-tab');

  $btn.addClass('active').siblings().removeClass('active');
  $('.panel').removeClass('show');
  $('#' + id).addClass('show');
});
  </script>
</body>
</html>

Watch out: jQuery 4 removed the old .toggleClass(false) and .toggleClass() forms with no class name, which used to remove every class from the element. Always name the class you want to toggle.

A useful naming habit is to describe the state, not the look: is-active, is-open or has-error rather than blue-bg or red-border. The JavaScript then says what is true (“this tab is active”), and the stylesheet decides what that looks like. If the brand colour changes next year, nobody has to edit the script.

In the tab demo above, notice the chain $btn.addClass('active').siblings().removeClass('active'). It activates the clicked button and deactivates its neighbours in one line – a very common jQuery pattern you will see again in jQuery Traversing.

Reading and writing styles with jQuery css()

.css('color') returns the computed value of the first matched element – the value the browser is actually using after all your CSS rules are applied. Colours come back in the browser’s format, such as rgb(29, 78, 216), even if your CSS said #1d4ed8. Ask for individual properties like borderTopWidth rather than shorthands such as border or margin, which are not guaranteed to return a value.

.css('color', 'teal') sets an inline style on every matched element. To set several properties at once, pass an object; property names can be written in CSS style ('font-size') or camelCase (fontSize). To remove an inline style again, set it to an empty string: .css('color', '').

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Reading and setting styles</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
    #quote { color: #1d4ed8; font-size: 18px; padding: 8px; border-left: 4px solid #1d4ed8; }
  </style>
</head>
<body>
  <p id="quote">Learning never exhausts the mind.</p>
  <button id="bigger" type="button">A+</button>
  <button id="smaller" type="button">A−</button>
  <button id="warm" type="button">Warm colours</button>
  <button id="reset" type="button">Reset</button>
  <p id="info"></p>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
const $quote = $('#quote');

function showInfo() {
  $('#info').text(`font-size: ${$quote.css('font-size')}, color: ${$quote.css('color')}`);
}

// Relative values: '+=2px' adds to the current size
$('#bigger').on('click', () => { $quote.css('font-size', '+=2px'); showInfo(); });
$('#smaller').on('click', () => { $quote.css('font-size', '-=2px'); showInfo(); });

// Object form sets several properties at once
$('#warm').on('click', () => {
  $quote.css({ color: '#b45309', 'border-left-color': '#b45309', backgroundColor: '#fff7ed' });
  showInfo();
});

// Empty strings remove the inline styles again
$('#reset').on('click', () => {
  $quote.css({ fontSize: '', color: '', borderLeftColor: '', backgroundColor: '' });
  showInfo();
});

showInfo();
  </script>
</body>
</html>

Always give units in jQuery 4

In jQuery 3, .css('font-size', 20) quietly added px for you. jQuery 4 only does this for a short list of properties: width, height and their min/max versions, top/right/bottom/left, margins, paddings and border widths. For anything else, such as font-size or line-height where a bare number has a different meaning, the number is passed through as it is. The habit that avoids surprises: write the unit yourself, as in .css('font-size', '20px').

Tip: jQuery css() also works with CSS custom properties: $('html').css('--brand', '#0a7a3d') changes a theme colour everywhere it is used. See CSS Variables for how to set those up.

Measuring elements

Next to the jQuery CSS methods, there are methods that return sizes as plain numbers in pixels, which is easier than parsing '240px' strings:

  • .width() / .height() – the content area only.
  • .innerWidth() / .innerHeight() – content plus padding.
  • .outerWidth() / .outerHeight() – content, padding and border.
  • .outerWidth(true) – the same plus margin, the full space the element takes.
// .card { width: 200px; padding: 16px; border: 2px solid; margin: 10px; box-sizing: content-box; }
$('.card').width();           // 200
$('.card').innerWidth();      // 232  (200 + 16 + 16)
$('.card').outerWidth();      // 236  (+ 2 + 2 border)
$('.card').outerWidth(true);  // 256  (+ 10 + 10 margin)

$('.card').width(300);        // sets the content width (px is added for width)

These names follow the CSS box model. If a layout only needs to adapt to the screen, use CSS (media queries, flexbox, grid) rather than measuring with JavaScript – measure only when your script truly needs the number.

Further reading

Key takeaways

  • Keep visual design in CSS classes and switch them with addClass, removeClass and toggleClass.
  • toggleClass(name, state) adds or removes based on a boolean; always name the class in jQuery 4.
  • .css(prop) returns the computed value; .css(prop, value) and .css({…}) set inline styles.
  • jQuery 4 adds px automatically only for a few properties like width and margin – write units yourself.
  • width(), innerWidth(), outerWidth() and outerWidth(true) measure following the box model.

Quick quiz

Check what you learned – pick an answer.

1. Which line marks a field red only when isValid is false?

2. In jQuery 4, what happens with .css('font-size', 20)?

3. Which method returns content + padding + border + margin?

Practice exercise

Add a "Dark mode" button to the tab demo. Clicking it should toggle a dark class on the body and change its own label between "Dark mode" and "Light mode".

Show a hint

After $('body').toggleClass('dark'), use $('body').hasClass('dark') to choose the label.

Show the solution
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Exercise: classes</title>
  <style>
    body { font-family: system-ui, sans-serif; padding: 16px; line-height: 1.5; }
    .tabs button { padding: 6px 14px; border: 1px solid #999; background: #f4f4f4; cursor: pointer; }
    .tabs button.active { background: #1d4ed8; color: #fff; border-color: #1d4ed8; }
    .panel { display: none; padding: 12px; border: 1px solid #ccc; margin-top: 8px; }
    .panel.show { display: block; }
    body.dark { background: #111827; color: #f3f4f6; }
  </style>
</head>
<body>
  <div class="tabs">
    <button type="button" data-tab="veg" class="active">Veg</button>
    <button type="button" data-tab="nonveg">Non-veg</button>
    <button type="button" data-tab="sweets">Sweets</button>
  </div>
  <div class="panel show" id="veg">Sambar rice, avial, curd rice</div>
  <div class="panel" id="nonveg">Chettinad chicken, fish fry</div>
  <div class="panel" id="sweets">Payasam, Mysore pak</div>
  <p><button id="theme" type="button">Dark mode</button></p>

  <script src="https://code.jquery.com/jquery-4.0.0.min.js"></script>
  <script>
$('#theme').on('click', (event) => {
  $('body').toggleClass('dark');
  const isDark = $('body').hasClass('dark');
  $(event.currentTarget).text(isDark ? 'Light mode' : 'Dark mode');
});
  </script>
</body>
</html>

Progress is saved in this browser only.