width & height

Objectives:

  • To study width and height in CSS.

File Location

You should be located in the following files:

   javascript-library
        └── 0-PreWork
            ...
            └── 2-CSS-Basics
                └── 06-width-height.css 
                └── 06-width-height.html

Sample Code

Let's go ahead and set up our HTML and CSS files. Make sure your HTML file looks like below:

<!DOCTYPE html>
<html>
  <head>
    <title>Width and Height</title>
    <link rel="stylesheet" type="text/css" href="06-widths-heights.css">
  </head>
  <body>
    <div class="wrapper"></div>
  </body>
</html>

Here is the sample CSS Code:

Discussion

Let's start talking about width and height. This is how we can shape the size of our HTML elements. There are a couple of different ways we can size things, we can use percentages, or explicit sizes like pixels. There is also auto which is the default way to size things, this means that the browser calculates the size.

Let's add some notes to our HTML right underneath our wrapper div:

More Examples

Let's look at a few examples. Add the following underneath your notes in your html:

So, let's style this div to give it a width of 50% and a height of 200px. See if you can do this yourself in CSS, then check below. Also, give the div a background color of something so you can really see the size.

Check and see if your CSS matches below!

Let's do another example, starting with saving the picture from here, save the image as lake.jpg for ease of reference in your HTML.

Add the following to your HTML, right before your closing wrapper div tag.

Let's style this image using width and height in our css. Again, see if you can figure out how to do it, and then check the CSS below.

Feel free to play with the values here, to see how these values affect the size of different elements.

Your files should look like the finished files below.

Finished Code

HTML:

CSS:

Next, we'll talk about borders.

Last updated