Controlling Document Flow
Learn to control the document flow of a simple HTML page.
In this lesson, we’ll look at how to use the CSS display property to convert block-level elements into inline elements and vice-versa. By controlling the way elements are displayed, we’re effectively controlling the document flow.
Controlling document flow using the CSS display
property
This chapter’s first example has the following HTML code:
<h1 class="border1 display-inline">We can control document flow via css display property</h1><div class="border1 display-inline">Just another div.</div><span class="border1 display-inline">Just another span.</span><span class="border1 display-inline">Yet another span.</span><div class="border1 display-inline">Yet another div.</div><div class="border1 display-inline">This is a third div on this page!</div>
We start our HTML structure with two block-level elements, an <h1>
and a <div>
tag. Their default behavior is to be displayed as block-level elements. Put differently, their CSS display
property is set by the browser to the value of the block
. In other words, modern browsers honor web standards by displaying the <h1>
and <div>
elements as block-level elements.
However, as we’ve seen before, we can override this default browser behavior using CSS (preferably CSS classes). With CSS, we can reset the display
property from the default behavior to something else.
Let’s see how we do it in our first example.
Switching block-level elements to inline, and vice-versa
Here’s our example’s CSS code:
.border1 { border: 5px solid #FFD166 }
.display-inline { display: inline }
The purpose of the first CSS class, border1
, is to give a 5-pixel gray border around any HTML element it is applied to. We’re applying this class to all the HTML elements in our first example to see what’s happening to all our elements.
The second CSS class in the above code is the display-inline
class, with a single property: value
pair: display: inline
. We could have given this CSS class any name we wanted, such as whatever
, or asdf
, or querty
—anything we wanted. However, if we were to determine what this class does just by looking at the HTML code where it’s applied as a value of the class
attribute, we’d have a hard time figuring it out.
Even if we know the meaning behind the name we give our CSS classes, our co-workers or anyone else reading our code would have difficulties understanding what’s going on. That’s why the CSS class name, display-inline
, is probably the best in this scenario.
Here’s the result of this override in the browser:
That’s it for our CSS code. Now we understand what’s happening in our HTML. We’re overriding the default display
property of all the elements in our first example and setting all the elements to display: inline
.
To see the original, default, normal document flow, we can simply comment the line that sets the display-inline
CSS class in our CSS. The updated code now looks like this: