We can control the width and height of an element using the
For the purpose of this lesson we will apply various
height attributes to a
<div> to see the effect.
To start, open the html file in your downloads folder corresponding to this lesson.
This file contains a
<div> in the
<body>, and one id selector (#div1) which has been applied to the
Preview the file in your browser to see what it looks like.
Here we can see the
<div> is 100%
width of the content area, and 500px in
height, with a blue
background-color. If we scale the browser window size up and down, the
<div> expands and contracts to suit the size of the content area.
CSS allows different values to be attributed to the
We will begin with
min-width can be used to specify the minimum amount of
width an element can be. Since the
width is currently set to 100% of the content area, it will automatically stretch and contract with the browser window.
If we wanted to maintain a minimum fixed width of 600 pixels we can apply the following declaration
Now when we expand and contract the window, you will notice that the
<div> maintains a minimum-width of 600px.
In addition to
min-width, we also have the
If we set the
max-width to 800pixels, the
<div> will not expand beyond this amount.
width can also be set to auto. This will make the
width of the element automatically size to it's container. In this case, the
<div> is not nested in another
<div> so it will expand to the full size of the browsers content area.
max-width, we also have
max-height. The value can be stated in pixels or percentage.
An important difference between the
height properties, is that setting the
height to 100%, will not result in your
<div> occupying 100% of your browsers content area.
In order to do this, we need to use the vh unit available with recent version of CSS. vh (Viewport Height) ensures that the element stretches to the full height (100%) of the devices viewport.
To use this feature, place the following declaration for the height: