How to set CSS styles with jQuery

Thumbnail of how to add css with jquery containing css code and Windows 10 desktop

Using jQuery to set CSS styles to your website can be really helpful when you want to automate the styling of your website and use dynamic cascading style sheets.


Let’s say you have the code below in your html page.

<div id="htop">
<h1>I'm haitian</h1>
<h1>I'm a blogger</h1>
<h1>I'm a programmer</h1>
<h1>I'm a YouTuber</h1>
<h1>I'm a system administrator</h1>
</div>

And you want to add all the text inside the div at the center of your screen. You can use the jQuery CSS method or addClass to do this.


First of all, you must have the jQuery library and it must be placed before your jQuery code. Here is the way to add the jQuery library:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>


I guess you will write your jQuery code in your html page. Below is the code you need if you are using the id htop.

<script>
$(function(){
$("#htop").css("text-align", "center");
});
</script>


If you want to use h1 tag to add the CSS (Cascading Style Sheets) code, use the code below to do so.

<script>
$(function(){
$("h1").css("text-align", "center");
});
</script>


To change the style only for the first or last h1, you can apply a filter to it. Here is the code you need to make that possible.

<script>
$(function(){
$("h1:first").css("text-align", "center");
//$("h1:last").css("text-align", "center");
});
</script>


To change the style only for even or odd elements, you can apply the filter below to make it possible.

<script>
$(function(){
$("h1:odd").css("text-align", "center");
//$("h1:even").css("text-align", "center");
});
</script>


You can also add multiple CSS codes at the same time in this way.

<script>
$(function(){
$("#htop").css({"color":"#ff0000", "background-color": "blue", "text-align": "center"});
});
</script>


Other way to add CSS code with jQuery is to use the append or addClass method. For example, if you have the Cascading Style Sheets (CSS) below:

.mytext {            
            text-align: center;
            color: red;
            font-size: 1em;
        }


To use the CSS above, you can create the mytext class on the element you want to apply it. For example, to apply it to everything in the div, you can call the div or the id htop. Here is an example how to use it.

<script>
$(function(){
$("div").addClass("mytext");
//$("#htop").addClass("mytext");
});
</script>


Video to show you how to add CSS with jQuery


What To Read Next


If you like the content of this post or if it has been useful to you, please consider sharing it on your social media and follow me on Facebook and Twitter for more exclusive content.