Advanced CSS
1. CSS Variables (Custom Properties)
CSS Variables allow you to store values in custom properties that can be reused throughout your CSS code. They make styling more maintainable and consistent.
Example: Using CSS Variables
<style>
:root {
--main-color: #3498db;
--padding: 20px;
}
.variable-box {
background-color: var(--main-color);
padding: var(--padding);
color: white;
}
</style>
<div class="variable-box">
This box uses CSS Variables.
</div>
2. CSS calc(), clamp(), min(), max()
These CSS functions allow dynamic calculations for property values:
calc()
— Performs calculations like addition or subtraction.clamp()
— Sets a scalable value with min and max limits.min()
/max()
— Choose the smallest or largest of multiple values.
Example: Using calc() and clamp()
<style>
.calc-box {
width: calc(100% - 40px);
padding: 20px;
background-color: #2ecc71;
color: white;
}
.clamp-text {
font-size: clamp(1rem, 2.5vw, 2rem);
}
</style>
<div class="calc-box clamp-text">
This box uses calc() and clamp() for width and font-size.
</div>
3. CSS Specificity and Inheritance
Specificity determines which style rule is applied when multiple rules match the same element. Inheritance allows some properties to be passed from parent to child elements.
Specificity Hierarchy (Lowest to Highest):
- Element selector (e.g.,
div
) - Class selector (e.g.,
.box
) - ID selector (e.g.,
#main
) - Inline styles (e.g.,
style="..."
)
Example: Specificity in Action
<style>
p {
color: green;
}
.text {
color: blue;
}
#text-id {
color: red;
}
</style>
<p id="text-id" class="text">
This paragraph is red because ID selector has the highest specificity.
</p>
This paragraph is red because ID selector has the highest specificity.
4. CSS !important and Best Practices
!important
forces a style to be applied regardless of specificity. It's useful in rare cases but should be avoided in general to maintain clean and predictable CSS.
Example: Using !important
<style>
.important-box {
background-color: green !important;
}
.override {
background-color: red;
}
</style>
<div class="important-box override">
This box is green because of !important.
</div>
Best Practices:
- Use meaningful class names for clarity.
- Avoid using
!important
unless necessary. - Keep specificity low for maintainable styles.
- Use variables and reusable components to reduce repetition.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.