Vanilla JavaScript Tutorial – Part Two: CSS Styling with JavaScript
Tags: javascript, programming
Published: 2021-05-11 17:56:22

Welcome to part two of the vanilla JavaScript adventure!

If you missed part one and would like to give it a try, <a style="color:dodgerblue;" href="https://shinetechnicallywrites.netlify.app/posts/vanilla-js-tutorial-part-one/">click here</a>.

<a style="color:dodgerblue;" href="https://codepen.io/mike-shine/pen/abpJNxN">Click here</a> for the starter code to part two, if you didn't complete part one or don't have the code anymore.

## Why CSS?

HTML and CSS are the peanut butter and jelly of the web development world; they always go hand in hand.

![Peanut butter and jelly sandwich](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cdros5cne3hggi5ly0aq.jpg "I'm worried about that plate falling.")

Since the basis of part one was using JavaScript in lieu of HTML, learning how to use JavaScript in lieu of CSS seems like a logical next step.

If you know basic HTML and basic JavaScript, chances are you have come in contact with CSS as well. CSS (short for Cascading Style Sheets) essentially controls the stylistic/visual component of the elements on the webpage: colors, fonts, text decoration, animations (sometimes), and more. If you need a more thorough explanation of CSS <a style="color:dodgerblue;" href="https://developer.mozilla.org/en-US/docs/Learn/CSS/First_steps/What_is_CSS">check out this MDN article</a>.


Let's continue where we left off with our part one code, and take a look at how to use CSS within JavaScript.

## Using CSS in your JavaScript file

As explained in previous articles, having separate files for HTML and CSS as well as many different files for different JavaScript components of your project is standard practice, and for good reason. Adhering to the principle of <a style="color:dodgerblue;" href="https://en.wikipedia.org/wiki/Separation_of_concerns">separation of concerns</a> allows for clearer organization of code, as well as reducing the chances of breaking changes occurring in the whole project because of a single faulty edit in one module. As in part one, we will still be using our `index.js` file for all of our CSS, to immerse fully into the JavaScript experience. However, please remember that 99% of projects you work on will not follow this practice, we are only doing it for the sake of learning how!

The general principle of styling in JavaScript is actually quite simple. The majority of this part of the tutorial will just be learning the most essential style features that you will probably need.

The basic pattern of styling in JavaScript is:

`<element to be styled>.style.<style property> = "desired outcome";`

That wasn't very well-explained. Let me give you a more concrete example to demonstrate; the next line of code will result in my `header` turning green:

`header.style.color = "green";`

![image of the example code, with header green colored](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t914tb0uhxly1esk4oqa.jpg)

That looks better. In that example, `header` is the element being acted upon, `style` is usually the keyword for accessing style properties, `color` is the style property that is being accessed, and `green` is the new desired color.

With our basic pattern of styling elements in mind, let's segue into our first CSS essential: color.

![Very colorful arches](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ywig2k5lq6fq022prun7.jpg)

## CSS Essential #1: Color

Color is one of the most important style elements in visual design. As such, there is substantial functionality built into CSS to support color; however, covering every aspect of using color in your styling could be an entire tutorial series by itself, so we will only be exploring a few basics.

Let's start by taking the example from the previous section and applying it here: change the color of your `header`. Use my code above, but instead of `green` you can select any basic color you like. Think color wheel/kindergarten colors, not the wackiest color you remember from the crayon box you used to have. For example:

`header.style.color = "orange";`

Your display should now look something like this, depending on what color you chose:

![example code with orange header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8nhthdqp3n2358en58tq.jpg)

Nicely done. The `color` property can be applied to text, backgrounds, borders, and pretty much any element on your webpage that you can think of.

Before we move on, go ahead and apply that same color you chose to your `text1` and `text2` elements.

Cool, now let's think about background color. White background is cool and all, but let's decide on something a little more exciting.

Use this code to modify your background color (you can substitute my color for a color of your choosing), then read on for an explanation:

`document.body.style.backgroundColor = "red";`

Good! Although this might seem quite different from changing the color of our header, it still follows our same basic pattern:

`<element to be styled>.style.<style property> = "desired outcome";`

For our background color styling, `document.body` is the element to be styled, the `style` keyword is still used, `backgroundColor` is the style attribute we are modifying, and `red` is my desired outcome.

One important distinction between CSS and JavaScript styling becomes relevant when modifying styling attributes that are more than one word (such as background color). In CSS, the syntax for such attributes is kebab-case (i.e. `background-color`). For JavaScript, the syntax is camelCase (i.e. `backgroundColor`).

Now then, with my choice of orange text and red background, my example looks like this:

![red background and orange text, difficult to read text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7oymvqs24y6lhpu68yle.jpg)

Bleh. That is not an attractive color combination, but more importantly it is quite difficult to read, even for users with standard vision. For users with vision impairments, this would be extremely difficult if not impossible to read. Always keep <a style="color:dodgerblue;" href="https://www.w3.org/WAI/standards-guidelines/wcag/">web accessibility standards</a> in mind when selecting color combinations! There are several tools (<a style="color:dodgerblue;" href="http://colorsafe.co/">like this one</a>) that help web developers/designers select color combinations that are appropriate for users of all vision levels.

With that in mind, I'm going to change my background color to something that will contrast the bright orange a little better.

`document.body.style.backgroundColor = "black";`

![orange text on black background](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/972nas0e3oho16nrvqgm.jpg)

Much better! We can use more colors than just the primary ones, however. To be precise, we have <a style="color:dodgerblue;" href="https://techterms.com/definition/rgb">16,777,216 color options</a> (although some may argue that because of transparency options, <a style="color:dodgerblue;" href="https://stackoverflow.com/questions/22285636/total-number-of-possible-color-combinations/53963230">we actually have a great deal more than that</a>).

There are three ways to specify color in web design:

1. <a style="color:dodgerblue;" href="https://encycolorpedia.com/html">Keyword</a>
2. <a style="color:dodgerblue;" href="https://en.wikipedia.org/wiki/RGB_color_model">RGB value</a>
3. <a style="color:dodgerblue;" href="https://en.wikipedia.org/wiki/Web_colors#Hex_triplet">Hex code</a>

In the interest of brevity, click on any of the three items above to learn more. The "Keyword" link leads to a list of all keywords that can be used in your color styling. The "RGB value" and "Hex code" links lead to respective explanations of the concepts, if you are unfamiliar.

Here are a couple examples of how each approach would look syntactically.

Keyword:

```javascript
header.style.color = "cornflowerblue";
text1.style.color = "chartreuse";
text2.style.color = "lightsalmon";
document.body.style.backgroundColor = "dimgray";
```

RGB:

```javascript
header.style.color = "rgb(100, 149, 237)";
text1.style.color = "rgb(127, 255, 0)";
text2.style.color = "rgb(255, 160, 122)";
document.body.style.backgroundColor = "rgb(105, 105, 105)";
```

Hex code:

```javascript
header.style.color = "#6495ed";
text1.style.color = "#7fff00";
text2.style.color = "#ffa07a";
document.body.style.backgroundColor = "#696969";
```

These three examples are visually identical, and should all display like this:

![same header and text with different colors from before](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0zpwfez27ttybl1jo01.jpg "Mature readers won't find the hex code for dimgray funny at all.")

This wraps up our color section, but you will continue to get practice with it along with other style elements.

## CSS Essential #2: Backgrounds

### `background-color`

In the previous section, we learned that we can modify the background color of the page with `document.body.style.backgroundColor = "color_goes_here";`. There is another important tidbit to know about the background color property, which is that it can be applied to individual elements as well. For example:

```javascript
const header = document.createElement('h1');
header.textContent = 'Vanilla JS practice';
header.style.backgroundColor = "red";
document.body.appendChild(header);

const text1 = document.createElement('p');
text1.textContent = 'Go hang a salami, I\'m a lasagna hog.';
text1.style.backgroundColor = "yellow";
document.body.appendChild(text1);

const text2 = document.createElement('p');
text2.textContent = 'Read the previous sentence backwards.';
text2.style.backgroundColor = "green";
document.body.appendChild(text2);
```

![three lines of text, each with a different background color](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/21isy51vhj6uvnkkeylx.jpg)

### `background-image`

In addition to a solid color, we can use images as backgrounds as well. Say, for example, we wanted to use this yummy-looking lasagna as a background image:

![lasagna](https://i.imgur.com/TUQLNdi.jpg "why oh why am I writing this section right before dinner")

We can use this image as our background one of two ways.

1. Image file saved to local filesystem

```javascript
document.body.style.backgroundImage = 'url("lasagna.jpg")';
```

2. Image file is online

```javascript
document.body.style.backgroundImage = 'url("https://imgur.com/TUQLNdi.jpg")';
```

![lasagna](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qc9wysjgyua3777j9t50.jpg)

### `background-repeat` and `background-size`

Oftentimes our background image does not perfectly match the size of the display. Therefore, we often have to stretch or repeat the image to make the background look complete.

The two main style properties that affect this are `background-repeat` and `background-size`.

`background-repeat` has four options:

1. `no-repeat` (image renders one time, default location is top left corner)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "no-repeat";
```

![no repeat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/moffjjqxuulfxx1wkev9.jpg "no-repeat")

2. `repeat-x` (image repeats horizontally across the screen)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "repeat-x";
```

![repeat-x](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqtczjh0glteej88g03q.jpg "repeat-x")

3. `repeat-y` (image repeats vertically across the screen)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "repeat-y";
```

![repeat-y](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tkoji0flf29olremfw4a.jpg "repeat-y")

4. `repeat` (default behavior; image repeats horizontally and vertically to fill the entire screen)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "repeat";
```

![repeat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k897h3qqmzmt30ajy5d2.jpg "repeat")

`background-size` has two main options:

1. `auto` (default behavior; image renders at its original size)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "auto";
```

![auto](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dnm9wpcb41h0fv3qcslp.jpg "auto")

2. `cover` (a single image stretches to cover the entire screen)

```javascript
document.body.style.backgroundImage = "url('https://biologydictionary.net/wp-content/uploads/2020/09/Walrus-1.jpg')";
document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "cover";
```

![cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o3t4w4udmc3w70ysmy1d.jpg)

## CSS Essential #3: Text emphasis

The main types of text/typographical emphasis include <span style="font-weight:bold">bold</span>, <span style="font-style:italic">italic</span>, and <span style="text-decoration:underline">underline</span>.

### Bold text

To make text <span style="font-weight:bold">bold</span>, set the `font-weight` property to the value "bold".

`text1.style.fontWeight = "bold";`

![bold text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/auinq1evjd215fgkcgpr.jpg "bold text")

### Italic text

To make text <span style="font-style:italic">italic</span>, set the `font-style` property to the value "italic".

`text2.style.fontStyle = "italic";`

![italic text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w1bbu8zmz4t6z0bt95w3.jpg)

### Underlined text

To make text <span style="text-decoration:underline">underlined</span>, set the `text-decoration` property to the value "underline".

`header.style.textDecoration = "underline";`

![underlined text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6huwcmy5kdsco72tvoz.jpg)

In addition to <span style="text-decoration:underline">underlined</span> text, the `text-decoration` property can also <span style="text-decoration:overline">overline</span> and <span style="text-decoration:line-through">line-through/strikethough</span> text.

```javascript
header.textContent = 'Vanilla JS practice';
header.style.textDecoration = "underline";

text1.textContent = 'Go hang a salami, I\'m a lasagna hog.';
text1.style.fontWeight = "bold";
text1.style.textDecoration = "overline";

text2.textContent = 'Read the previous sentence backwards.';
text2.style.fontStyle = "italic";
text2.style.textDecoration = "line-through";
```

![all text emphasis styles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vssdfffyrmoeealybnnq.jpg)

## CSS Essential #4: Borders

Borders have several properties, which can be set and modified individually. However, in my experience most developers use the shorthand `border` property, which combines the `border-width`, `border-style`, and `border-color` properties. Instead of writing three lines of code...

```javascript
header.style.borderWidth = "5px";
header.style.borderStyle = "dotted";
header.style.borderColor = "salmon";
```

...one could write one line of code:

```javascript
header.style.border = "5px dotted salmon";
```

![header with border](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eji9c8muvw7xyff9bdke.jpg)

When using the `border` property, the only parameter that is required is `border-style`. `border-width` and `border-color` are optional, and default to 3px and black respectively.

As with color, borders are big topic with lots of different options for customization and specification. Rather than explain and show all the options in this tutorial, <a style="color:dodgerblue;" href="https://www.w3schools.com/css/css_border.asp">click here if you wish to learn more about CSS border properties and options</a>.

## Try it yourself – Task

Congrats on getting this far! To try to synthesize the information presented in this tutorial, try this task on your own. Of course, if you need to refer back to earlier parts of this article for information, you are encouraged to do so!

<span style="font-weight:bold;">Your task</span>: <span style="text-decoration:underline">Make a square on the screen, below your text.</span> This is very open-ended, and there are nearly limitless ways to do this.

<span style="font-weight:bold; font-style:italic; color:limegreen">Extra Credit</span>: If you complete this task, try to complete it one or two MORE times using different approaches.

Before you get started, you should do some independent Google research on CSS `height` and `width` properties. I didn't cover those properties in this tutorial, but you may need them now.

If you get stuck, scroll down for a few hints, and down to the next section for a couple sample answers. Good luck!

![Patrick Star rooting for you](https://media.giphy.com/media/12XDYvMJNcmLgQ/giphy.gif)

.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>

<span style="font-weight:bold;">Hint #1</span>: The first step to completing this task is to create a new element, likely a `<div>`. From there, you can use a combination of the style properties you learned in this tutorial to make a square.

.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>

<span style="font-weight:bold;">Hint #2</span>: Have you looked up the `height` and `width` properties yet? You may need to set those properties on your new element to give it a defined area.

.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>
.
</br>

<span style="font-weight:bold;">Hint #3</span>: If you can't get a square to appear on the screen, re-check the basic stuff:

- Have you used `document.body.appendChild(YOUR_SQUARE_HERE)`?

- Have you given your square some sort of style feature that makes it visible? Double check your syntax for every line.

## Try it yourself – Example solutions

I hope you were able to make a square! If you were not, or if you want to see some more ways to do it, check out some example solutions:

1. Using the `border` property:

```javascript
const newSquare = document.createElement('div');
newSquare.style.border = "solid";
newSquare.style.height = "200px";
newSquare.style.width = "200px";
document.body.appendChild(newSquare);
```

![square made with border property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wg2wuz0ymlzf6owbw8n7.jpg "square made with border property")

</br>

2. Using the `background-color` property:

```javascript
const newSquare = document.createElement('div');
newSquare.style.backgroundColor = "red";
newSquare.style.height = "200px";
newSquare.style.width = "200px";
document.body.appendChild(newSquare);
```

![square made with background color property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfuwqcrundnothvys2bt.jpg "square made with background color property")

3. Using the `background-image` property:

```javascript
const newSquare = document.createElement('div');
newSquare.style.backgroundImage = "url('purple-square.png')"
newSquare.style.height = "200px";
newSquare.style.width = "200px";
document.body.appendChild(newSquare);
```

![square made with background image property](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3107i9bghdu20hz263fp.jpg "square made with background image property")

## Conclusion

That was but a <span style="font-weight:bold">brief</span> introduction to all that CSS has to offer, and how to implement it in JavaScript. I hope you learned a lot that you can apply in your own projects! Be sure to check out the third part of this tutorial, which will (I think) cover modals in JavaScript.

---

_Attributions_:

- Peanut butter and jelly image by Freddy G, linked from Unsplash
- Colorful festival image by Robert Katzki, linked from Unsplash
- Lasagna image by sunorwind, linked from Unsplash
- Horseback rider image by Mikayla Storms, linked from Unsplash
- Patrick Star gif is the property of ViacomCBS, Inc. Linked from GIPHY