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
Working with element for CSS
You can put your CSS rules into an HTML document using the <style> element. This tag is placed inside <head>...</head> tags. Rules defined using this syntax will be applied to all the elements available in the document.
Syntax
<head>
<style>
/* CSS rules go here */
selector {
property: value;
}
</style>
</head>
Example
Following is an example of embedded CSS using the <style> element:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Output
The above HTML will display a page with a light beige background, and a maroon heading positioned 40 pixels from the left margin.
Adding Styles with JavaScript
You can also dynamically add CSS styles using JavaScript by creating a <style> element:
// Create a style element
let styleElement = document.createElement('style');
// Add CSS rules
styleElement.textContent = `
body {
font-family: Arial, sans-serif;
}
.highlight {
background-color: yellow;
padding: 10px;
}
`;
// Append to head
document.head.appendChild(styleElement);
// Apply the class to an element
document.body.innerHTML = '<p class="highlight">This text is highlighted!</p>';
Key Points
- The
<style>element must be placed within the<head>section - CSS rules inside
<style>apply to the entire document - You can have multiple
<style>elements in one document - JavaScript can dynamically create and modify
<style>elements
Conclusion
The <style> element provides an easy way to embed CSS directly into HTML documents. This approach is useful for small projects or when you need document-specific styling rules.
Advertisements
