ArticleZip > Vanilla Javascript Set Style On Body

Vanilla Javascript Set Style On Body

Are you looking to add some flair to your web page using plain JavaScript? Setting styles on the body element with vanilla JavaScript is a simple yet powerful way to customize the look of your website. In this guide, we'll walk you through the steps to set styles on the body element using pure JavaScript. Let's dive in!

To get started, you first need to get a reference to the body element in your HTML document. You can do this by selecting the 'body' element using the `document.body` property. This gives you access to the body element, allowing you to manipulate its styles dynamically.

Once you have a reference to the body element, you can use the `style` property to set various CSS styles. For example, let's say you want to change the background color of the body to a light blue. You can achieve this by setting the `backgroundColor` property of the style object like so:

Javascript

document.body.style.backgroundColor = 'lightblue';

This line of code changes the background color of the body element to light blue. You can customize the color by using any valid CSS color value such as hex, RGB, or color names.

In addition to setting the background color, you can also modify other styles such as text color, font size, margin, padding, and more. Here's an example of changing the text color of the body to white and setting the font family to Arial:

Javascript

document.body.style.color = 'white';
document.body.style.fontFamily = 'Arial';

By combining different style properties, you can achieve a wide range of design possibilities for your web page.

Furthermore, you can set multiple styles in a single statement by separating each style with a semicolon. This allows you to apply multiple changes simultaneously. For instance, if you want to set both the background color and text color of the body element, you can do so like this:

Javascript

document.body.style.cssText = 'background-color: lightblue; color: white;';

Using the `cssText` property, you can specify multiple CSS styles in a single line for convenience.

Remember that setting styles directly in JavaScript using the `style` property overrides any existing inline styles and may also override styles defined in external stylesheets. Make sure to test your changes to ensure they render as expected on your webpage.

In conclusion, manipulating styles on the body element using vanilla JavaScript is a straightforward way to enhance the visual appeal of your website. By leveraging the `style` property, you can dynamically adjust various aspects of the design to create a more engaging user experience. Experiment with different styles and have fun customizing your web page!

×