FlexBox Layouts
The CSS3 answer to floats
We’ve already used a flex layout for the header,
and now we’ll explore what it is and how it works.
The display
values you may be familiar with
are inline, block, inline-block, and none.
CSS3 introduces some new display values,
one of which is the mighty flex.
Setting display: flex
on a container
allows us to do fancy sizing on its children.
Here are a few examples of layouts
you can easily achieve using flexbox.
Image credit CSS Tricks
In the “old days”, layouts like these were achieved
(with difficulty) using inline-block elements or floats.
In this chapter we will explore flexbox as a
developer and mobile friendly option for layout.
Columns
We can use flexbox to arrange elements
in a responsive horizontal layout.
Columns should never contain so much text
that you can’t view the whole thing at once.
We will create some panels advertising
the various content on our site.
In your home
page, create a new container,
with the extra class panel-links
.
<div class="container">
<h1>Hello!</h1>
</div>
<div class="panel-links container">
</div>
Inside the new container, add three links:
<div class="panel-links container">
<a href="/shop.html">
<h2>Online Shop</h2>
<p>
Browse the yummy treats we have to offer
before you come by for a visit.
</p>
</a>
<a href="/gallery.html">
<h2>Photo Gallery</h2>
<p>
See photos of our space and our food so
you feel at home even before you arrive.
</a>
<a href="/contact.html">
<h2>Visit Us</h2>
<p>
Find our address and open hours, we'd love
to see you. You can even give us a call.
</a>
</div>
In your stylesheet, create a style
for the panel links:
.panel-links a {
display: block;
text-decoration: none;
color: black;
text-align: center;
background-color: white;
border: 1px solid #333;
border-radius: 3px;
padding: 20px;
}
.panel-links a:hover {
background-color: lightblue;
}
To lay out the panels horizontally,
use display: flex
on the parent.
.panel-links {
display: flex;
align-content: space-between;
}
.panel-links a {
display: block;
text-decoration: none;
color: black;
text-align: center;
background-color: white;
border: 1px solid #333;
border-radius: 3px;
padding: 20px;
}
.panel-links a:hover {
background-color: lightblue;
}
We can add spacing between using margins:
.panel-links a {
display: block;
text-decoration: none;
color: black;
text-align: center;
background-color: white;
border: 1px solid #333;
border-radius: 3px;
padding: 20px;
margin-right: 20px;
}
And we can remove the margin from
the last panel using a pseudo selector.
.panel-links a:last-of-type {
margin-right: 0;
}
Challenge: Two-Column Layout
Use flexbox to add a Google Map beside
contact information on your contact
page.
Loading...