How to Include One CSS File in Another?
Last Updated :
20 Jan, 2025
Improve
Here are the methods to include one CSS file in another:
Method 1. Using @import Rule
The @import rule allows you to import one CSS file into another, enabling modularity and reusability of styles.
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1 class="title">Hello, GeeksforGeeks!</h1>
<p class="content">This is an example of including one CSS file in another.</p>
</body>
</html>
styles.css
@import url('additional-styles.css');
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.title {
color: green;
text-align: center;
}
.content {
font-size: 16px;
line-height: 1.5;
}
additional-styles.css
<!DOCTYPE html>
<html>
<head>
<title>To include one CSS file in another</title>
<style>
@import "style.css";
h1 {
color: green;
}
.geeks {
color: black;
background-image: linear-gradient(to right, #DFF1DF, #11A00C);
position: static;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<div class="geeks">
GeeksforGeeks: It is a computer science
portal. It is an educational website. Prepare for the
Recruitment drive of product based companies like
Microsoft, Amazon, Adobe etc with a free online placement
preparation course.
</div>
</body>
</html>
- The @import rule in styles.css includes additional-styles.css, ensuring that all styles from the additional file are applied.
- This approach keeps styles modular and reusable across multiple files.
Method 2. Using Preprocessors like SCSS
If you’re using SCSS (Sass), you can use the @import directive to include one file in another.
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<h1 class="header">Welcome to GeeksforGeeks!</h1>
<p class="text">This is a demo of including CSS files with SCSS.</p>
</body>
</html>
main.scss
@import 'variables';
@import 'typography';
body {
margin: 0;
padding: 0;
font-family: 'Roboto', sans-serif;
}
_variables.scss
$primary-color: #008000;
$secondary-color: #333;
_typography.scss
.header {
color: $primary-color;
text-align: center;
font-size: 2rem;
}
.text {
color: $secondary-color;
font-size: 1rem;
line-height: 1.6;
}
- SCSS files use the @import directive to include partials (like _variables.scss and _typography.scss).
- After compiling SCSS, a single main.css file is generated for use in the HTML.