By default, if you don't set an explicit width and height for an element, the element will take on default sizes. These are slightly different, and the width and height they take on depends on whether the element is a block element or an inline element.
Block elements
- width - takes up 100% of the width of it's container element (if the container element is the body element then it will take up the width of the web-page)
- height - increases for it's content to fit inside. the more content it contains, the taller the element becomes. if there is no content, the element has a height of zero!
Example 1
<div style="border: dashed 1px rgb(102,102,102)">
<strong>Example 1</strong><br>
Look at the border. See how this element is just tall enough to contain it's content?
</div>
Output
Look at the border. See how this element is just tall enough to contain it's content?
I used a div element here as div elements are block elements by default.
Inline elements
- width - increases for it's content to fit inside. the more content it contains, the wider the element becomes. if there is no content, the element has a width of zero
- height - increases for it's content to fit inside. the more content it contains, the taller the element becomes. if there is no content, the element has a height of zero
Example 2
<span style="border: dashed 1px rgb(102,102,102)">
<strong>Example 2</strong>
</span>
Output
Example 2
See how the span element is just tall and wide enough to contain it's content?
Well, with CSS you can also set a width and a height explicitly for any element. You do this, surprise surprise using the width property, and the height property. If the contents of the element become wider than the width you set, then they will wrap onto a newline. If the contents of the element become taller than the element, then... the contents will display outside of the element!
Example 3
<div style="width: 100%; height: 30px; border: dashed 1px black;>
<strong>Example 3</strong><br>
Yadda yadda yadda
</div>
Output
Yadda yadda yadda
The only difference then between a div element and a span element when you explicitly set the width and/or height of the element is that a div will always be on a line of it's own. It will force a single new line but, if you explicitly set the height then the height is removed from the flow of the document, although the element itself will still be within the flow of the document.
With CSS you can also set the width and height of an element using a percentage.
<div style="border: dashed 1px rgb(102,102,102); width: 50%;">See how this example div takes up 50% of the width of this section?</div>
Output
Try it yourself, then take the quiz.