jQuery Change CSS Dynamically – It’s Easy!

Sam Deering

change-css-with-jquery

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 
$('p').css({"color":"green"});

//float all divs with class .left
$('div.left').css('float');

//change all elements with class .bg-red to have a red background
$('.bg-red').css({"background-color":"red"});

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
$('#mydiv').removeClass('colors');

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)
$('#div').removeClass('red').addClass('green');

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.

1
<script type='text/javascript'>
$(document).ready(function() {
	//preload image (add timestamp to prevent cache)
	var newimgsrc = 'http://dab1nmslvvntp.cloudfront.net/wp-content/uploads/jquery4u/2011/03/jquery-plugins2.jpg?' + (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'});
	newimg.show();
});
</script>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • 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

      @Thomas,

      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
      $(‘container’).css({‘max-width':’500px’});
      }
      else
      {
      //set min width
      $(‘container’).css({‘min-width':’200px’});
      }
      });

      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
        $(‘container’).css({‘max-width’:’500px’});
        }
        else
        {
        //set min width
        $(‘container’).css({‘min-width’:’200px’});
        }
        });
        i tried

        $(‘#checkbox’).bind(‘change’, function()
        {
        $(this).attr(‘checked’) != true) {
        //set max width
        $(‘container’).css({‘max-width’:’500px’});
        }
        else
        {
        //set min width
        $(‘container’).css({‘min-width’:’200px’});
        }
        });

        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

      @greg,

      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 = ‘http://www.sitepoint.com/wp-content/uploads/jquery4u/2011/03/jquery-plugins2.jpg?’ + (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’});
    newimg.show();
    });

    so it changes through different background images on refresh.

    Thanks
    J

  • Viwe Mavayi

    Hello

    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

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

    The image is just not showing can you help me.

    • http://jquery4u.com/ jQuery4u

      Hi View, 

      Some of your code you posted appears broken, could you paste it into a jsfiddle for me?

      http://jsfiddle.net/ 

      Thanks,
      Sam

  • 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.

    http://www.handycss.com/how/how-to-create-css-dynamically/

    • http://jquery4u.com/ jQuery4u

      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 | umutZafer.blog()

  • http://www.facebook.com/profile.php?id=552152719 Emiro Pérez Pérez

    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?

    Thanks.

  • Hitarth Trivedi

    good one

  • vikas

    wow