[!] [=title "Week 8: Display"] [=content-]
Every tag in a page has a display. This controls how it's sized and positioned by the layout engine.
There are three main values for display: inline, block, and inline-block.
Most elements are inline or block by default. For example:
<style>
#inline-element {
display: inline; /* this is already set automatically - just putting it here for clarity */
background-color: yellow;
}
#block-element {
display: block; /* this is already set automatically - just putting it here for clarity */
background-color: green;
}
#inline-block-element {
display: inline-block; /* this is *not* set automatically, divs are block by default */
background-color: red;
}
</style>
<span id="inline-element">
text<br />
text part 2
</span>
<div id="block-element">
text<br />
text part 2
</div>
<div id="inline-block-element">
text<br />
text part 2
</div>
Gives this result:
textThis is important! Notice that the yellow inline element fits around the text - meaning the size and shape is the same as the contents, even when they're not an even square. Conversely, the green block element fills the whole width - even though the content is much smaller than that. And finally, the red inline-block element fills the bounding box: the smallest rectangle you can draw around the content.
Sizes don't always work the same way! For instance, if we change the previous demo code:
<style>
#inline-element {
display: inline; /* this is already set automatically - just putting it here for clarity */
background-color: yellow;
width: 100px;
height: 100px;
}
#block-element {
display: block; /* this is already set automatically - just putting it here for clarity */
background-color: green;
width: 100px;
height: 100px;
}
#inline-block-element {
display: inline-block; /* this is *not* set automatically, divs are block by default */
background-color: red;
width: 100px;
height: 100px;
}
</style>
<span id="inline-element">
text<br />
text part 2
</span>
<div id="block-element">
text<br />
text part 2
</div>
<div id="inline-block-element">
text<br />
text part 2
</div>
Gives this result:
text
block and inline-block both respect the width, but inline completely ignores it!
Displays are extremely important to understand. There are actually quite a few more beyond these basic ones, but it's critical to understand the basic ones before moving onto weirder things like flexbox and grid. I highly recommend reading more on display at Mozilla Developer Network (warning: pretty advanced - we haven't covered all of the material on that page!).
[/] [#template.html]