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 set border width, border style, and border color in one declaration with JavaScript?
To set the border width, style, and color in a single declaration, use the border property in JavaScript. This property accepts a shorthand value that combines all three border properties.
Syntax
element.style.border = "width style color";
The order is: width, style, color. You can also specify individual sides using borderTop, borderRight, borderBottom, or borderLeft.
Example: Setting Border with Button Click
<!DOCTYPE html>
<html>
<body>
<button onclick="setBorder()">Set Border</button>
<div id="box" style="padding: 20px; margin: 10px;">
<p>Demo Text</p>
<p>Click the button to add a border</p>
</div>
<script>
function setBorder() {
document.getElementById("box").style.border = "3px solid #ff6b6b";
}
</script>
</body>
</html>
Different Border Styles
<!DOCTYPE html>
<html>
<body>
<div id="box1" style="padding: 10px; margin: 5px;">Box 1</div>
<div id="box2" style="padding: 10px; margin: 5px;">Box 2</div>
<div id="box3" style="padding: 10px; margin: 5px;">Box 3</div>
<script>
// Solid border
document.getElementById("box1").style.border = "2px solid blue";
// Dashed border
document.getElementById("box2").style.border = "4px dashed red";
// Dotted border
document.getElementById("box3").style.border = "1px dotted green";
</script>
</body>
</html>
Common Border Values
| Width | Style | Example |
|---|---|---|
| thin, medium, thick 1px, 2px, 3px |
solid, dashed, dotted double, groove, ridge |
"2px solid #333" "thick dashed red" |
Setting Individual Border Sides
<!DOCTYPE html>
<html>
<body>
<div id="specialBox" style="padding: 20px; margin: 10px;">
Different borders on each side
</div>
<script>
const box = document.getElementById("specialBox");
box.style.borderTop = "3px solid red";
box.style.borderRight = "2px dashed blue";
box.style.borderBottom = "4px dotted green";
box.style.borderLeft = "1px solid orange";
</script>
</body>
</html>
Conclusion
The border property provides a convenient shorthand to set width, style, and color in one declaration. Use individual border properties like borderTop when you need different styles for each side.
Advertisements
