To get started with the Flex Display we will create a very simple HTML and CSS.
HTML Structure
In HTML consider we have a div
container which displays the list of items
<div class="container">
<div class="flex-item item-1">Item 1</div>
<div class="flex-item item-2">Item 2</div>
<div class="flex-item item-3">Item 3</div>
<div class="flex-item item-4">Item 4</div>
<div class="flex-item item-5">Item 5</div>
</div>
As you can see we have a parent div
with class container
and the parent div contains the child div with class flex-item
and individual class of each item.
CSS Design
lets create a css class to make the look feel good
body {
margin: 0;
}
.container {
border: 6px solid black;
}
.flex-item {
color: white;
font-size: 1.5rem;
padding: 1rem;
text-align: center;
}
.item-1 {
background-color: #B4BF35;
}
.item-2 {
background-color: #B95F21;
}
.item-3 {
background-color: #1C4C56;
}
.item-4 {
background-color: #CfB276;
}
.item-5 {
background-color: #6B0803;
}
After this what we will get to display is:
Now let us focus on the very first property which is a display property
To create a flex container we make use of the display property and set it to a value of flex
So in the CSS first create a class for flex which would be named as d-flex
.d-flex {
display: flex;
}
And Add this d-flex
class after the container class in html.
After this what we will get to display is:
As you can see the items are laid out from left to right also you can see the container is having a 100% width as it behaves as a block-level element.
Display inline flex
So if you change the diplay: flex
to display: inline-flex
/* You can create a seperate class for inline flex as `d-inline-flex` */
.d-flex {
display: inline-flex;
}
After this what we will get to display is:
As you can see the black border is now wrap around the flex items. The container only takes up enough width to accommodates its children.
Make Sure the display property is always set or none of the other property is going to work on the flex container.
DEMO
See the Pen
Flexbox by rehmaanali (@geekstrick)
on CodePen.