Friday, June 12, 2015

Aligning Elements using CSS3 “Flex” options

CSS3 introduces the “Flex” options that makes aligning elements extremely easy! It is currently supported in all the major browsers (not supported in IE 11 and below);

Let’s say that I want to align four elements in a line:

clip_image002[4]

The CSS:

.container {
padding
: 0;
margin
: 0;
list-style
: none;
display
: flex;
}

.item
{
background
: green;
padding
: 5px;
width
: 150px;
height
: 150px;
margin
: 10px;
line-height
: 150px;
color
: white;
font-weight
: bold;
font-size
: 3em;
text-align
: center;
-ms-border-radius
: 30%;
border-radius
: 30%;
}


The only new property here is “display: flex”. Not only that flex aligns the elements in a single line it also makes them responsive when the container size changes (overriding the element’s explicit width property;

clip_image003[5]

If you wish to keep the element’s original width you can add the flex-wrap:wrap property which will break the line if needed:

clip_image004[5]

You can reverse the order of the elements that break the line using flex-wrap:wrap-reverse:

clip_image005[5]

You can align the whole line to center or to the first/last item (flex-start/flex-end) using the justify-content property. By default it is set to flex-start:

clip_image007[5]


.container {
padding
: 0;
margin
: 0;
list-style
: none;
display
: flex;
flex-wrap
: wrap;
justify-content
: center;
}


There are two more options for justify-content: space-between and space-around which adds equal spaces between each element:

clip_image009[9]


.container {
padding
: 0;
margin
: 0;
list-style
: none;
display
: flex;
flex-wrap
: wrap;
justify-content
: space-between;
}


If you choose space-around then the first and the last elements will also have the same spaces from the borders.

Vertical Alignment

You can vertically align the elements using flex-direction:column.

clip_image010[4]


Using align-items you can control the vertical starting point (the same like justify-content):

clip_image011[4]


.container {
padding
: 0;
margin
: 0;
list-style
: none;
display
: flex;
flex-wrap
: wrap;
align-items
: center;
flex-direction
: column-reverse;
}


So far we’ve applied the flex properties only to the elements container. We can also apply some flex properties directly on the elements, like making some item be 3 times bigger than the rest:

clip_image013[4]


.container > .grow {
flex-grow
: 3;
}


I’m using the flex-grow property on the wanted item and setting it’s value to 3 as for 3 times bigger.

Flex has more properties that can help you easily align your elements . Go ahead and try!

No comments:

Post a Comment