Sitemap
Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Manipulating the DOM With HTML, JavaScript, and CSS: Part 2

--

In Part 1 of this entry, we discussed how to set up a boiler plate HTML file and use JavaScript to manipulate the DOM . This blog will be a little shorter and focus on some basic CSS functionality and best practices for styling an application. We will begin by making some minor adjustments to the HTML, but first let’s talk about CSS.

Cascading Style Sheets

CSS or Cascading Style Sheets describe how our HTML elements will be displayed on a web page. We use CSS ‘selectors’ to select specific HTML elements from our DOM and apply styles to them; this could be color, font-size, position on the page, and just about anything you can think of. In this blog we will take our web application from this:

Our Un-styled app from the end of the last course

To This:

Completed Styling

Minor Adjustments

Before we jump into CSS we are going to make some minor adjustments to the JavaScript and HTML in order to make styling easier. We will start with the index.js file.

The last time we edited the JavaScript file, we left it looking something like this:

Old JavaScript file

We’re just going to make a slight adjustment here. Notice on lines 23 and 24 we create an ‘li’ and a ‘button’ element, then we append the button element to the li on line 36. This was fine for a basic application, but to make adding styles easier it would make more sense to wrap both the list item and the button in a div, and then add the div. Our JavaScript would then look like this:

updateList function updated

In addition to adding a div, we give each element a className attribute, which is the equivalent to adding a class to an HTML tag. If this were to be written out in HTML, it would look like this:

The li and button tags are rendered inside the div tag

There will also be one more minor adjustment in the index.html file. We are going to wrap the label, input, and button tags inside a div and give it a class of ‘new-todo-container’.

Importing CSS

Now that we have made some adjustments to our HTML and JavaScript to allow for easier styling, we can being styling! We will create a file called styles.css in our main directory and import it into our HTML. As you may have guessed, the .css extension indicates that the contents of that file will be written in CSS.

To import this file into the HTML, we use a link tag which will define the relationship between this file and an external source. The link tag will have a ‘rel’ attribute which describes the relationship between this document and the one we are linking to, in this case it will be defined as stylesheet. The link tag will also have an ‘href’ which is the URL of the document we are linking, styles.css. The index.html file should now look as follows:

The link tag goes in the head of the html document

CSS Selectors

In CSS we use selectors to specify which part of the document we want to add style to. You can view a list of all the selectors here, but we will go over some of the most commonly used selectors to help you get started styling your application. We can start with the most basic of selectors, which is selecting by HTML Element Tag name.

Looking at our HTML file, we can see all of our elements exist within the body tag. By typing ‘body’ and adding curly brackets, we use the body tag as a selector to add whatever style we put in the brackets! Let’s try the following code to change the background color.

‘background’ instead of ‘background-color’ will also work here

Refresh your browser and you will see the changes!

Notice the layout of the app is slightly different because of the HTML and JavaScript changes we made earlier

Selecting by Element, however, is not recommended. Though we may be working with a small application, most web pages are very large and have lots of different components that use the same elements in many different places. For this reason we have classes. As I mentioned in Part 1 of this blog, classes allow us to easily select which HTML element we want to reference in our stylesheet. By typing the class name with a . (period) in front of it, we can reference any element regardless of the name as long as it has that class name.

Here we are referencing the div element with the class name ‘new-todo-container’ that wraps our label, input, and button tag for adding a todo element. The ‘text-align’ property set to center sets the text within a selected element to generate in the center of that element. Since a div tag takes the full width of the screen, the text appears in the middle of the screen!

Another common CSS selector is the ‘id’ attribute. To reference an element with a specific id, simply place a # (hashtag) in front of the id name. Id selectors do in fact take priority over other selectors, so it is not always a great idea to use them. In general, using class selectors is the best way to reference your HTML for styling.

Specificity

Specificity in CSS is what dictates what styles will be applied to what elements, especially where styles overlap. CSS files are read from top to bottom, using the most recent style as priority for the element. If we have a CSS file that defines all the h1 tags as blue on line 5, then redefines them as red later on on line 25, the most recent declaration will be used, and the h1 tags will be red.

That is pretty standard behavior on programming in general, but let’s say you have some CSS defining h1 as blue, but also a class selector settings a specific class to red. Something like the following:

order does not matter in this case, because the class selector will take precedence when present on the HTML element

If we apply that class ‘an-h1-tag’ to an h1 element, it will override the general h1 tag styling and the class selected styling will take precedence.

Another way to demonstrate specificity is by stacking or combining selectors. If we take the HTML from out application as an example, we have a div that is a parent to a label, input and button tag. We have not designated the label with any type of class or id, so we could just specify some CSS by adding styles to all label tags, but what if we use a label somewhere else in our application and want a different style applied? By combining thee selector for the div that contains the label and the label itself, we can specify that we only want to add style to that particular label(s) that exists within that particular div.

Font weight determines the thickness of characters

Notice the above contains a space between ‘.new-todo-container’ and ‘label’. The space indicates the next selector will be a child of the first, if we were to remove the space this CSS would look for an element with the class of ‘new-todo-container’ and is also a label. We can chain together as many selectors as necessary, and you may find it very necessary when working on very large applications.

Using Pictures

If you have some background in HTML, you may be familiar with using the <img/> tag to display images in your view from URLs. But what if we wanted to use our own downloaded images? And what if we want to set the background as an image? We can use CSS to solve achieve this.

First, we begin by creating a folder called ‘assets’ in the main directory of our project. The name of the folder can be anything you want, but since it will be storing the ‘asset’ for our app, it is common practice to name this folder ‘assets’.

To find the image we want, I like to use a website called unsplash.com to get free stock images. I decided to go with a photo I found of a nice blue sky and a palm tree. Another CSS tip I have found is that images and color schemes give your application a certain feel that generates an emotional response. Since our app is a To Do app, I decided to go with this blue sky image because it feels positive and uplifting, who knows, it may even inspire the user to get more items on their list done! There is a lot of psychology behind color schemes as well, and I would be lying to you if I said I know all about it, but if you are really interested I recommend taking the time to research what color schemes invoke what emotions.

Once we download our image, we put it in the ‘assets’ folder. Now we can access it from anywhere in our app! Turning the the styles.css file, we have an existing background of plain orange. Considering that is fairly ugly, we will happily change it using the following syntax:

The relative path starts with a . to indicate current directory, but you could also use ‘/’ with no period if you are in the root directory. This will depend on the structure of your application folders and files

Here we set the height of the background to 100% to cover the entire body element, and our ‘background’ style takes a parameter ‘url’ which is passed the relative file path to our image! ‘Background-size’ here tells us that we want the image to be resized to cover 100% height of the body, rather than retain its original dimensions from where we downloaded it.

CSS Grid and Flexbox

There are two more very popular and important properties in CSS I want to talk about here and they are CSS Grid and Flexbox. My styling abilities increased dramatically when I learned about CSS Grid and started to incorporate it into my applications. Both Flexbox and Grid are tools in CSS to help designing the layout of the page easier. I have written an entire blog about Grid and FlexBox you can read here, but for now understand that Flexbox is for 1 dimensional layout, and Grid is for 2 dimensional layout.

In our application, we are going to make our To Do list a grid, that way each to-do div can be its own row in the grid. We set the display property to grid, then define the template rows and columns for our grid to indicate how many rows and columns we will need. We can use almost any unit here, pixels or percentages or em, but we are going to use the ‘fr’ unit. The ‘fr’ unit is a fraction of the entire space, so by setting one row to ‘1fr’ and the second row to ‘2fr’, the first row would be 33.33% of the space while the second row would be the remaining 66.67%, or 1/3 and 2/3 of the total grid space. r

list-stlye: none removes the bullet points that are added by default when rendering unordered list items

The argument above lets us no that the minimum row size could be 0, will the maximum could be 1fr. Im not going to go over all the styles applied in this application, that would be unnecessarily and long to read. A lot of the CSS styles are in fact very self explanatory, for example grid-row-gap determines a distance between each row in a grid. You could likely infer what ‘grid-column-gap’ would achieve based on this…

Wrapping Up

Instead of walking through every bit of CSS for our application, I am going to post the finished file with comments to describe some of the less obvious stylings. We have covered a lot here, and most importantly covered the basics and some concepts to get you started with adding CSS to your applications. A lot of CSS is trial and error, and a lot is experimenting with different ideas to see what will make your application look good.

Finished CSS
Our finished application

If you have made it this far in the blog I am assuming you are fairly new to Web Development, and if that is the case my advice to you is get familiar with the basics first! Get experience using selectors and nesting selectors, make sure your styles are specific to exactly the elements you want them to be, and work with Grid and Flexbox to build the layout of your application. There are many libraries you could use for styling your application, but a solid understanding of CSS and how it works is necessary for front end Web Development.

When the video is complete, this blog will be linked to a YouTube video that goes over in detail the same concepts covered here as well as adding the styling I did not cover. Feel free to leave feedback here, ask questions, and check out the video. And as always, Happy Coding!

Resources:

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Aidan McBride
Aidan McBride

Written by Aidan McBride

I am a Front End Engineer and graduate of Flat Iron coding bootcamp. Currently I work in the regulatory industry using React.

Responses (1)