Web Design

Divs

The HTML/CSS Div Element

What are Divs?

A div is an element that can be used for almost anything. Text, images, shapes, etc. Without CSS, they don’t have any purpose.

Creating Divs

To create a div, just open <div> and close it </div>. To make these actually meaning full, let’s give it some style attributes.

Width and Height

Since divs don’t have a size, we need to give them dimensions. We can do this by stating width and height. We can use px(preferred), percentage, etc, for our dimensions

<div style=”width: 50px; height: 50px”></div>

This gives it a width and height of 50px. But you won’t see it until we give it a color. Let’s add a background color.

    <div style=”width: 50px; height: 50px; background-color: cyan;”></div>

Creating a CSS File

Now that we have a div that creates a cyan square, let’s make it easier to duplicate. On your dashboard, create a new CSS file, named styles.css. Head back over to your index.html file, and add the styles.css to the file in the header.

    <head>
        <link rel="stylesheet" href="styles.css">     

This will allow us to put CSS into the styles.css file and have the index.html be able to read it. Copy 'width: 50px; height: 50px; background-color: cyan;' from the div, and paste it into the CSS file.

Now type into the styles.css file, '. block {' above the line we pasted, and '}' below it. Your styles.css file should look like this:

.block {
    width: 50px; 
    height: 50px; 
    background-color: cyan;
}        

What does this do?

We have created a CSS Class named block. Every time we create a new class, we write “.” then the name of the object we are making. If we are adding styles to a paragraph, link, heading, or any premade tag, we don’t add the “.”.

If you reload the page, you won’t see anything. That’s because we never told the div element to use the block object. Go into index.html and change your div to this:

<div class=”block”></div>

Now, the HTML will know, “I need to go into styles.css and find the block class.” Now, if you reload the page, you will see that the block we created is back.

Nested Elements

You can add more elements within divs. You can add images, text, links, etc. The div can be used for almost anything in HTML and CSS.

chevron_up