How to change CSS using jQuery?

Viewed 493274

I am trying to change the CSS using jQuery:

$(init);
    
function init() {
    $("h1").css("backgroundColor", "yellow");
    $("#myParagraph").css({"backgroundColor":"black","color":"white");
    $(".bordered").css("border", "1px solid black");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
    <h1>Header</h1>
    <p id="myParagraph">This is some paragraph text</p>
</div>

What am I missing here?

11 Answers

The .css() method makes it super simple to find and set CSS properties and combined with other methods like .animate(), you can make some cool effects on your site.

In its simplest form, the .css() method can set a single CSS property for a particular set of matched elements. You just pass the property and value as strings and the element’s CSS properties are changed.

$('.example').css('background-color', 'red');

This would set the ‘background-color’ property to ‘red’ for any element that had the class of ‘example’.

But you aren’t limited to just changing one property at a time. Sure, you could add a bunch of identical jQuery objects, each changing just one property at a time, but this is making several, unnecessary calls to the DOM and is a lot of repeated code.

Instead, you can pass the .css() method a Javascript object that contains the properties and values as key/value pairs. This way, each property will then be set on the jQuery object all at once.

$('.example').css({
    'background-color': 'red',
    'border' : '1px solid red',
    'color' : 'white',
    'font-size': '32px',
    'text-align' : 'center',
    'display' : 'inline-block'
});

This will change all of these CSS properties on the ‘.example’ elements.

 If you have one css:

   $("p").css("background-color": "pink");

If you have more than one css: 

  $("p").css({"background-color": "pink", "font-size": "200%"});

Or you can use:

var style ="background-color:red;";
$("p").attr("style", style);

$(function(){ 
$('.bordered').css({
"border":"1px solid #EFEFEF",
"margin":"0 auto",
"width":"80%"
});

$('h1').css({
"margin-left":"10px"
});

$('#myParagraph').css({
"margin-left":"10px",
"font-family":"sans-serif"
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="bordered">
<h1>Header</h1>
<p id="myParagraph">This is some paragraph text</p>
</div>

Related