How to apply CSS in a particular div element using jQuery ?
Last Updated :
15 Nov, 2021
In this article, we will set the CSS of a div element using jQuery. We will use the CSS property to set the CSS.
Approach: We will create a div element with some text and hyperlinks. Then we will use jQuery to apply CSS to the div element. jQuery comes with the function .css() where we can get and set CSS of any element. We will use it for the div element.
Syntax:
<script>
$("div").css("css-property","value");
</script>
Example 1: Using a Simple CSS
HTML
<!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" />
< meta name = "viewport"
content = "width=device-width" />
< script src =
</ script >
</ head >
< body >
< div id = "links" >
< h1 >Welcome to GeeksforGeeks</ h1 >
< a href =
Data structures
</ a >
< a href =
Algorithms
</ a >
</ div >
< script >
// Changing text color to green
// and aligning to center
$("div").css("color", "green");
$("div").css("text-align", "center");
</ script >
</ body >
</ html >
|
Output:
Example 2: Using hover effect on element
We will use the hover function of jQuery which takes two functions. The syntax is
$(element).hover(
function(){
// CSS during hover
},
function(){
// CSS when not hovering
},
);
Here is the example code.
HTML
<!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" />
< meta name = "viewport"
content = "width=device-width" />
< script src =
</ script >
</ head >
< body >
< div id = "links" >
< h1 >Welcome to GeeksforGeeks</ h1 >
< a href =
Data structures
</ a >
< a href =
Algorithms
</ a >
</ div >
< script >
// Changing text color to green
// and aligning to center
$("div").css("color", "green");
$("div").css("text-align", "center");
// Using hover function
$("h1").hover(
// First function is for during hover
function () {
$(this).css("font-size", 32);
},
// Second function is for before
// or after hover
function () {
$(this).css("font-size", 24);
$(this).css("transition-duration", "1s");
}
);
</ script >
</ body >
</ html >
|
Output
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...