Displaying Elements
If a web page were like a piece of lined notebook paper and the elements were what you wrote on the page:
- Some elements would be written on their own line.
- Other elements would be able to share a line with other elements.
We can apply this concept to how elements are displayed on a site, from small ones like <a>
and <p>
to larger container-like ones such as <div>
, <section>
, or <body>
.
Elements are either displayed on the block level or the inline level.
Block elements take up the entire width
of whatever they’re inside of. However, this can be changed (as well as the height
).
By default, block elements are rendered on their own line by themselves.
The <div>
and <p>
elements are common block elements:
<div></div>
<p>Hello, World! What shall I research on Wikipedia today?</p>
Each element is displayed on its own line. Let’s add some styles to further visualize this example:
div {
width: 100%;
height: 100px;
background-color: red;
}
p {
border: 1px solid blue;
}
The <div>
block element now has a defined width
and height
, as well as a background-color
. Since it is rendered before the <p>
paragraph element, the page will render like so:
Inline elements only take up as much space as needed, and other elements may appear beside them! The <a>
anchor element is a very popular inline element because links are always being used within blocks of text (e.g., a Wikipedia article with lots of links to other places).
In the previous example, if we wrap “Wikipedia” into a link with the <a>
anchor element (within the <p>
paragraph element):
The “Wikipedia” text becomes a link that stays in line with the parent <p>
element.
If we wanted to change the default display of these elements, we would use the display
property!
a {
display: block;
}
Note: Unlike block elements, inline elements cannot change their width
or height
properties.
When we change the default display of the <a>
element from inline
to block
, this is the result:
There is one other display property to explore…inline-block
!
When you set an element to display: inline-block
, you get the best of both worlds:
- It can share the same line with other inline elements.
- Despite being inline, its width and height can be changed.
For example:
#block {
background-color: lightcoral;
height: 100px;
}
#inline {
background-color: lightblue;
}
#inline-block {
background-color: lightgreen;
}
This renders something like the following:
Note:
As shown above, some elements, like the
<div>
element, behave weirdly when set to justinline
. Any content inside remains, but the width and height of the<div>
are practically not there anymore.