How to override the CSS properties of a class using another CSS class ?
To override the CSS properties of a class using another class, the `!important` directive can be employed. In CSS, `!important` signifies the significance of a style declaration, ensuring it takes precedence over other styles, regardless of their specificity.
Syntax:
element1 {
property-x: value_y !important; /* This will be applied. */
}
element2 {
property-x: value_z; /* This will not be applied. */
}
Example: Implementation to show to override the CSS properties by using !important property.
html
<!DOCTYPE html>
< html >
< head >
< title >Using !important property</ title >
< meta charset = "utf-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1" >
< link rel = "stylesheet" href =
< link href =
rel = "stylesheet" >
< link href =
rel = "stylesheet" >
< style >
h1 {
text-align: center;
color: green;
}
.my_fav_font {
font-family: 'Indie Flower', cursive !important;
/* This will be applied. */
}
.my_para {
font-family: 'Mansalva', cursive;
/* This will not be applied. */
text-align: justify;
background-color: powderblue;
font-size: 130%;
}
</ style >
</ head >
< body >
< div class = "container" >
< h1 >GeeksforGeeks</ h1 >
< hr />
< p class = "my_fav_font my_para" >
Cascading Style Sheets,
fondly referred to as CSS, is a simply designed language
intended to simplify the process of making web pages
presentable. CSS allows you to apply styles to web pages.
More importantly, CSS enables you to do this independent
of the HTML that makes up each web page.
</ p >
</ div >
</ body >
</ html >
|
Output:
Example 2: Implementation to show to override the CSS properties by using specific selector and then overriding.
HTML
<!DOCTYPE html>
< html >
< head >
< title >Without Using !important</ title >
< meta charset = "utf-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1" >
< link rel = "stylesheet" href =
< link href =
rel = "stylesheet" >
< link href =
rel = "stylesheet" >
< style >
.body-style {
text-align: center;
font-family: 'Indie Flower', cursive;
/* Apply font to body directly */
}
.my_para {
font-family: 'Mansalva', cursive;
text-align: justify;
background-color: powderblue;
font-size: 130%;
/* Overriding property */
color: red;
}
</ style >
</ head >
< body class = "body-style" >
< div class = "container" >
< h1 >GeeksforGeeks</ h1 >
< hr />
< p class = "my_para" >
Cascading Style Sheets,
fondly referred to as CSS, is a simply designed language
intended to simplify the process of making web pages
presentable. CSS allows you to apply styles to web pages.
More importantly, CSS enables you to do this independent
of the HTML that makes up each web page.
</ p >
</ div >
</ body >
</ html >
|
Output:
Last Updated :
24 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...