Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to import styles from another style sheet in CSS
The CSS @import rule allows you to import styles from another stylesheet into your current CSS file. This rule must be placed at the very beginning of your stylesheet, before any other CSS rules.
Syntax
@import "stylesheet-url";
@import url("stylesheet-url");
@import url("stylesheet-url") media-query;
Basic Import Example
Here's how to import an external CSS file into your stylesheet −
<!DOCTYPE html>
<html>
<head>
<style>
@import url("https://fonts.googleapis.com/css2?family=Arial:wght@300;700&display=swap");
body {
font-family: Arial, sans-serif;
margin: 20px;
line-height: 1.6;
}
.title {
color: #2c3e50;
font-weight: 700;
font-size: 24px;
}
.content {
color: #34495e;
font-weight: 300;
margin-top: 15px;
}
</style>
</head>
<body>
<h1 class="title">Imported Font Example</h1>
<p class="content">This text uses an imported Google Font with different font weights.</p>
</body>
</html>
A webpage displays with the title in bold Arial font and content in lighter Arial font weight, both imported from Google Fonts.
Import with Media Queries
You can also import stylesheets conditionally based on media queries −
<!DOCTYPE html>
<html>
<head>
<style>
@import url("https://fonts.googleapis.com/css2?family=Roboto:wght@400&display=swap") screen;
body {
font-family: Roboto, sans-serif;
margin: 20px;
padding: 20px;
background-color: #f4f4f4;
}
.container {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.text {
color: #333;
font-size: 16px;
}
</style>
</head>
<body>
<div class="container">
<p class="text">This font is imported only for screen media.</p>
</div>
</body>
</html>
A white container with rounded corners displays text in Roboto font, which is imported specifically for screen display.
Key Points
- The
@importrule must be placed at the very beginning of your CSS, before any other rules - You can use either quoted URLs or the
url()function - Media queries can be added to conditionally import stylesheets
- Multiple
@importrules can be used in a single stylesheet
Conclusion
The @import rule enables modular CSS development by allowing you to split your styles into separate files and import them as needed. This approach helps maintain organized and reusable stylesheets across your projects.
Advertisements
