The HTML style attribute is used to apply inline CSS styles directly to an HTML element.
Definition and Usage
➔ This can be used to see a quick visual representation of a specific element, but it is recommended to use a separate stylesheet or <style> block.
Syntax
//In HTML
<div id="sample"
style='text-align: center; padding: 30px; background: rgb(100, 100, 100, 0.4); border:2px solid black;'>
<h1>HTML style attribute Example</h1>
<p>The HTML style attribute is used to apply inline CSS styles directly to an HTML element</p>
</div>
//In Javascript
<script>
let element = document.querySelector("#sample");
element.style.border = "2px solid black";
element.style.textAlign = 'center';
element.style.padding = '30px';
element.style.background = 'rgb(100, 100, 100, 0.4)';
//OR
element.style.cssText = 'text-align: center; padding: 30px; background: rgb(100, 100, 100, 0.4); border:2px solid black;';
//OR
Object.assign(element.style, {
textAlign: 'center',
padding: '30px',
background: 'rgb(100, 100, 100, 0.4)'
});
</script>
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| style | Global Attributes |
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML style attribute Example</title>
</head>
<body>
<h3>HTML style attribute Example</h3>
<p>style attribute is used to apply inline css styles</p>
<div id="sample"
style='text-align: center; padding: 30px; background: rgb(100, 100, 100, 0.4); border:2px solid black;'>
<h1>HTML style attribute Example</h1>
<p>The HTML style attribute is used to apply inline CSS styles directly to an HTML element</p>
</div>
</body>
<script>
//let element = document.querySelector("#sample");
/* element.style.border="2px solid black";
element.style.textAlign= 'center';
element.style.padding= '30px';
element.style.background= 'rgb(100, 100, 100, 0.4)'; */
//OR
/* element.style.cssText = 'text-align: center; padding: 30px; background: rgb(100, 100, 100, 0.4); border:2px solid black;'; */
//OR
/* Object.assign(element.style, {
textAlign: 'center',
padding: '30px',
background: 'rgb(100, 100, 100, 0.4)'
}); */
</script>
</html>
Click on the "Try it Now" button to see how it works.