HTML Flex Layout

Overview

The flex layout will layout the elements inside a div either horizontally or vertically. The layout will resize elements designated as flex elements in order to accomodate the size of the container div.

Applying Flex Layout


To specify the flex style, yo need to add "display:flex;" to the style attribute of a div element. Any elements within that div will have the flex layout applied to them.


<div style="height:100px;display:flex;flex-direction: row;">
  
</div>
				


In addition, a flex-direction needs to be specified. If the direction is specified as "row", the components will be laid out horizontally. If the direction is specified as "column", the elements are laid out vertically.

Specifying Size


When elements are placed inside a display=flex div, they will be laid out according to the flex rules. If a height or width is specified, the browser will use those values. If no height, or width is specified, but the element has flex:number in its style, the browser will stretch to the element according to a set of rules.

In the following example, the flex direction specifies that the elements are to be laid out horizontally. One element is specified to have a width of 100px. The other element is labeled "flex:1;", which instructs the browser to stretch the width of the element to fill the remaining space.




<div style="height:100px;display:flex;flex-direction: row;">
  <div style="height:100px;background-color: lightgreen;width:100px;"></div>
  <div style="height:100px;background-color: lightblue;flex:1;"></div>
</div>
				
Try it!

Flex Ratios


When an element is specified as a flex element with a flex attribute like "flex:1;", the number after the colon specifies how the element scales relative to other elements. That is, an element with "flex:2;" scales twice as much as an element specified as "flex:1;"


<div style="height:100px;display:flex;flex-direction: row;">
 <div style="height:100px;background-color: lightgreen;flex:1;"></div>
 <div style="height:100px;background-color: lightblue;flex:2;"></div>
</div>
				
Try it!