środa, 19 czerwca 2013

CSS Flexible box layout module - part 2 - Basics

In the beginning...

In the beginning we would like to know some vocabulary:
Flex container – DOM element which contains flex items. It defines available spaces for its children.

To create a flex container use display property with “flex” or “inline-flex” value;

section {
  display: -webkit-box; /* OLD: Safari, iOS, Android browser, older WebKit browsers. */
  display: -moz-box; /* OLD: Firefox (buggy) */
  display: -ms-flexbox; /* MID: IE 10 */
  display: -webkit-flex; /* NEW, Chrome 21+ */
  display: flex; /* NEW: Opera 12.1, Firefox 22+ */
}


Because it is still Candidate Recommendation, browsers implement it as an experiment, so we need to use prefixes. There are 3 syntaxes – new (standard), old and mid (legacy syntax). In the end of this article I've added some links explain syntax for some of properties. In this article I use standard syntax without prefixes.

flex item – child element of flex container
main axis – axis defined by flex-direction property in flex container, by default it is X-axis (row/row-reverse value)
cross-axis – perpendicular to the main axis.

CSS Flexible box layout module - part 1 - Introduction

Long long time ago...

Maybe not so long, but some years ago all layouts used tables as a base. It was nice time and almost everything was possible using table cells. But document structure and semantic were completely unreadable and layouts were not flexible. So we got “CSS box model” which we still use today. It is semantic way (especially if use HTML5 tags) to create layout. But it still generates problems. Especially related to calculation of width/height of elements. Setting width of element on 10% and adding border and padding increases element width from 10% to 10% + border + padding.



Flexbox

Flexible box layout is like an answer for all those troubles. It is flexible, semantic and uses available space without specific units. Sounds great, but what exactly does it mean?

Imagine you have a DOM element like section, inside it you want to position n children elements, and you want every of those children to have the same width. As long as you don't know number of children elements it is hard to code. But flexbox gives a possibility to do this without any calculation. How? It is quite simple, but first we need to know how flexbox works.