127 views
Types of CSS
CSS (Cascading Style Sheets) can be classified into different types based on their usage and context. Here are the main types of CSS:
- Inline CSS: In this type, CSS is applied directly within the HTML elements using the
style
attribute. It’s not recommended to use inline CSS extensively, as it mixes content and presentation, making maintenance and styling updates challenging. Example:
<p style="color: blue; font-size: 16px;">This is an inline styled paragraph.</p>
- Internal CSS (Embedded CSS): In this type, CSS is placed inside the
<style>
element in the head section of an HTML file. The CSS rules apply only to that specific HTML file. Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS Example</title>
<style>
body {
background-color: lightgray;
}
h1 {
color: navy;
}
</style>
</head>
<body>
<h1>This is a heading.</h1>
</body>
</html>
- External CSS: In this type, CSS rules are placed in a separate CSS file with a .css extension. The CSS file is linked to the HTML file using the
<link>
element in the head section. This is the most recommended way of organizing CSS, as it separates content and presentation, making it easier to maintain and reuse styles across multiple pages. Example:
HTML (index.html):
<!DOCTYPE html>
<html>
<head>
<title>External CSS Example</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading.</h1>
</body>
</html>
CSS (styles.css):
body {
background-color: lightgray;
}
h1 {
color: navy;
}
- CSS Frameworks: CSS frameworks are pre-written CSS files that include a collection of styles and components to speed up web development. These frameworks provide a set of ready-to-use styles and layouts, helping developers build responsive and consistent websites quickly. Examples of CSS frameworks include Bootstrap, Foundation, and Bulma.
- CSS Preprocessors: CSS preprocessors are scripting languages that extend the capabilities of CSS. Developers write code in these preprocessor languages, which are then compiled into standard CSS. Popular CSS preprocessors include Sass (Syntactically Awesome Style Sheets) and Less.
- CSS-in-JS: CSS-in-JS is a modern approach where CSS styles are written and managed directly in JavaScript files. It allows developers to create and manage component-based styles within their JavaScript code. Popular libraries for CSS-in-JS include Styled Components and Emotion.
These different types of CSS offer varying degrees of flexibility, organization, and scalability, and the choice depends on the specific needs and preferences of the project and the development team.