This lesson focused on using JavaScript to dynamically modify the style of elements on a webpage. The .style
property of JavaScript provides an interface to change or add CSS styling to an element.
- The
.style
property lets you get or set inline styles of an element. - It provides a way to add to or modify CSS styling of a webpage directly through JavaScript.
The general format for using .style
is:
selector.style.cssProperty = "value";
Example: To set the width of an image:
firstImg.style.width = "400px";
- Selector: Choose the HTML element you want to style.
- .style Property: Used to access the style of the chosen element.
- CSS Property: Decide which style property you want to change.
- Value: Set the desired value for that property.
Example: To set a div's background color to purple:
div1.style.backgroundColor = "purple";
-
CSS properties that have two words are written in camel case when using them in JavaScript.
-
Remove any hyphens and capitalize the first letter of the second word.
CSS JavaScript background-color backgroundColor font-size fontSize
Example:
header.style.backgroundColor = "black";
header.style.color = "lightGreen";
- JavaScript provides a powerful tool in the
.style
property to dynamically adjust styles. - Remember to use camel case for CSS properties that are typically hyphenated when using them in JavaScript.
For those interested in diving deeper, consider looking into:
Happy coding! 🚀