By Sam Deering

jQuery Change CSS Dynamically – It’s Easy!

By Sam Deering


CSS Function Demo

Changing your website styles dynamically is now the craze that is taking over the web! In this short, but sweet post I will explain how to do some simple yet effective CSS tricks using jQuery. This is a must know for all you avid jQuery developers!

Change Specific CSS Element

It’s really easy to change CSS with jQuery this is the format of the .CSS() function.

$('jQuery selector').css({"css property name":"css property value"});

Here are some common examples:

//change paragraph text colour to green 

//float all divs with class .left

//change all elements with class .bg-red to have a red background

Nest Your jQuery CSS Commands

It is handy to know jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. This will not only save you alot of time but it looks prettier!

newimg.css({'background-image': 'url('+newimgsrc+')'});
newimg.css({'position': 'absolute'});
newimg.css({'height': '70px'});
newimg.css({'width': '200px'});
newimg.css({'top': '68px'});
newimg.css({'right': '2px'});

Is exactly the same as:

newimg.css({'background-image': 'url('+newimgsrc+')', 'position': 'absolute', 'height': '70px', 'width': '200px', 'top': '68px', 'right': '2px'});

Remove CSS Styles

There are two main ways to remove CSS styles not much difference between them.

1. You can remove the class associated with the page or element

//remove text color from a div

2. You can also remove CSS styles on certain elements directly

//remove text color from a div
$('#mydiv').css('color', '');

This is also a nifty jQuery CSS trick to remove and add a class in the same call.

//change text color from red to green (classes specified in stylesheet)

Extending Existing Styles Values

You may wish to just extend a style based upon it’s current value. For example, if an element’s padding-left was 10px then the following code would result in a total padding-left of 25px.

.css( "padding-left", "+=15" )

jQuery .CSS() Function Property

As most of you avid jQuery developers know, as of jQuery 1.4, .css() allows us to pass a function as the property value. This is handy for returning current CSS values to determine changes.

$('div.example').css('width', function(index) {
  return index * 50;

Common Background CSS Changes

Here are some examples of changing background CSS.

$('#myDiv').css('background-image', 'my_image.jpg');
// OR
$('#myDiv').css('background', 'path/to/image.jpg');
// OR
$('#myDiv').css("background-image", "url(/myimage.jpg)");  

<br /><br />
<h2>A Full Code Example - Set Div Background Image</h2>
This is a full example of jQuery Code to set a background image into a div dynamically when the page is loaded.

[code lang="js"]
<script type='text/javascript'>
$(document).ready(function() {
	//preload image (add timestamp to prevent cache)
	var newimgsrc = '' + (new Date().getTime());
	var newimg = $('#header');
    //replace the image
	$('#header').css("background-image", "url("+newimgsrc+")");
	newimg.css({'background-image': 'url('+newimgsrc+')', 'position': 'absolute', 'height': '70px', 'width': '200px', 'top': '68px', 'right': '2px'});;
  • Thomas Rynell

    Great Article!
    Could you pls show how to modify/toggle a css class with a checkbox or button.
    I would like to alter max-width and/or min-width in the below class:

    .container {
    margin: 0 auto;
    max-width: 1600px;
    min-width: 1000px;
    padding-top: 12px;
    width: 95%;

    regards T

    • jquery4u


      Interesting question! I guess your trying to alter the width of an element when the user checks a box and reset it when a user unchecks the box.

      This could be done by creating a ‘change’ bind event on the checkbox and then if it’s checked apply max width or unchecked apply min width. Something like this:

      $(‘#checkbox’).bind(‘change’, function()
      $(this).attr(‘checked’) != true) {
      //set max width
      //set min width

      Haven’t tested this but hope it gives you the idea!

      • ymerdrys

        how do i use that code ?
        $(‘#checkbox’).bind(‘change’, function()
        $(this).attr(‘checked’) != true) {
        //set max width
        //set min width
        i tried

        $(‘#checkbox’).bind(‘change’, function()
        $(this).attr(‘checked’) != true) {
        //set max width
        //set min width

        cant see anything on my page.
        what i want to do is i have this css code
        .item-scroll {
        overflow: auto;
        width: 100%;
        height: 393px;
        and this
        .item-scroll_off {
        width: 100%;
        height: auto;
        the first code shows my content in nice box with scroll
        other just show all without scroll.
        then i like user to be able to switch the scroll of box on/off
        with some code
        i was hoping i could use that code for that
        my best regards

  • greg

    this arrticle is wrong!
    newimg.css(‘position’: ‘absolute’);

    doesn’t work, this is correct:
    newimg.css(‘position’, ‘absolute’);

    • jquery4u


      Yeah the syntax does work but it needs to be declared as an object literal notation. Like this:

      newimg.css({‘position’: ‘absolute’});

      Thanks, I’ve updated the post! :)

  • Pingback: Inserting an Element then Cloning it using jQuery | jQuery4u()

  • Pingback: 10 jQuery Enhanced CSS Buttons | jQuery4u()

  • Pingback: Confluence: Kuali Rice()

  • Pingback: jQuery Change CSS Dynamically « JqueryHeaven()

  • julian

    How do you change

    $(document).ready(function() {
    //preload image (add timestamp to prevent cache)
    var newimgsrc = ‘’ + (new Date().getTime());
    var newimg = $(‘#header’);
    //replace the image
    $(‘#header’).css(“background-image”, “url(“+newimgsrc+”)”);
    newimg.css({‘background-image’: ‘url(‘+newimgsrc+’)’, ‘position’: ‘absolute’, ‘height’: ’70px’, ‘width’: ‘200px’, ‘top’: ’68px’, ‘right’: ‘2px’});;

    so it changes through different background images on refresh.


  • Viwe Mavayi


    Im using Mvc and jquery, i would like to know how can I get an image to display.
    I have

    and inside my scrip tags I have

                var imageSource = $(‘#images’);
                var newimg = $(‘.logo’);
                newimg.css({‘background-image’, ‘Url(‘+imageSource+’)’});

    The image is just not showing can you help me.

  • Hera butt

    It may be useful sometimes to provide your visitors with the option to change the appearance of your website. Perhaps you want to provide theme support for your site. Or you may simply want to provide a bigger font size version of your site for older users who may not be able to read the small-sized text you use by default. This article describes how you can use JavaScript to dynamically change the cascading style sheets, or CSS, of your website.

    • Thanks Hera, I’m thinking of doing a complete redesign soon, not got the time at the moment though.

  • Pingback: 10 Awesome CSS Format Tools | jQuery4u()

  • Vishal Panchal

    useful 1

  • martin bats

    Small question just for understanding: Is it possible to change a css file (example: I use style1.css as default and press the button to change to style2.css) and keep it that way the entire time I surf on my website? When I tried your demo, I changed the website from light to black, but when I pressed a menu-item, it turned white again… Is there a way to stick with the dark one the entire time I’m on the site? Thanks!

  • Pingback: jQuery ile CSS |

  • Hi, I’m extending of $ and I need to change the width property to element by id.

    like : $(‘#jforms[componentController-component-campo10-0]’).css({“width”:”100px”});

    but don’t work for my.
    can you help me ? please.

  • Petr Dušek

    Hi. Could someone explain me where jQuery store the css changes? Here you are my example task: I have got a text editor on my website and I am using jQuery to modify the css of the editor. Then I would like to save the content of the editor – but not only html, css as well. Is it possible to create some css file this way?


  • Hitarth Trivedi

    good one

  • vikas


  • Marcos Figueira

    Hi there! I have a probably stupid question. :-) I made a pure css pop-up. I know how to trigger that using a button/link BUT I need it triggered automatically on page load. Can someone help with the JavaScript?

    on load???

    Open Modal


  • Marc

    I’m styling up a client portal where the background image needs to be different according to the particular section of the portal the user is looking at. The thing is this is .net and the source code cannot be changed, it is produced dynamically. I’m assuming I can’t achieve this with pure CSS, so how would I do it with jQuery?


  • Isa Paine

    I want jQuery to upload the image, but it never loads to the page from this jQuery, even though the alert() shows the url has been updated. Help.

    My html5 page references a css background-image and that image loads. But then I want this image (below) to load, it never loads and simply puts a blank space on the page.

    $(document).ready(function (event) {
    setTimeout(function () {
    $(“.headerPrimary”).css(‘padding-bottom’, $(window).height() + ‘px’);
    $(“.headerPrimary”).css(‘height’, $(window).height() + ‘px’);
    $(“.headerPrimary”).css(‘width’, $(window).width() + ‘px’);

    $(‘.standardPageHeaderFormat’).css({ ‘background-image’: “url(‘../images/LightStat_Web_index-v2-900×735-
    withLogoHigher.png’)” });


    }, 500);


  • Jose Andrés Reyes

    Hi there! I’m creating a single page website where the menu is fixed. What I want to do is change the color of the words in the menu (Home, About Me, Contact, etc.) every time the menu gets to a different section of my page (when it is in the first section, the menu is white, the second section, the menu should be blue colored). Can you guys help me out with this?


  • great help, Thanks!

  • Amit

    Here is another good tutorial to change the Style Dynamically on

Get the latest in JavaScript, once a week, for free.