CSS Property flex








The flex property is a property for the Flexible Box Layout module.

The flex property sets the length of the item, relative to the rest of the flexible items inside a container.

The flex property is a shorthand for the flex-grow, flex-shrink, and the flex-basis properties.

The flex-shrink and flex-basis are optional.

Summary

Initial value
0 1 auto
Inherited
no
CSS Version
CSS3
JavaScript syntax
object.style.flex="1"
Animatable
yes

CSS Syntax

flex: flex-grow flex-shrink flex-basis|auto|initial|inherit;

Property Values

flex-grow
A number setting how much to grow relative to the rest of the flexible items
flex-shrink
A number setting how much to shrink relative to the rest of the flexible items
flex-basis
item length . Could be "auto", "inherit", or a number followed by "%", "px", "em" or any other length unit
auto
1 1 auto
none
0 0 auto




Browser compatibility

flex Yes 11.0 (10.0 -ms-) 28.0 (18.0 -moz-) Yes Yes

Example

<!DOCTYPE html>
<html>
<head>
<style> 
#main {<!--   w  w  w.j  a  v  a 2  s.  c  o m-->
    width: 220px;
    height: 300px;
    border: 1px solid black;
    display: -webkit-flex; /* Safari */
    display: flex;
}

#main div {
    -webkit-flex: 1;  /* Safari 6.1+ */
    -ms-flex: 1;  /* IE 10 */    
    flex: 1;
}
</style>
</head>
<body>

<div id="main">
  <div style="background-color:red;">RED</div>
  <div style="background-color:blue;">BLUE</div>  
  <div style="background-color:gree;">Green div with more content.</div>
</div>

</body>
</html>

Click to view the demo





Example 2

The following code creates the border layout with flex properties.

<!DOCTYPE html>
<html class=''>
<style>
.flex-container {<!-- ww  w. j a v  a2s .  c om-->
  padding: 0;
  margin: 0;
  list-style: none;
  height: 200px;
  
  -ms-box-orient: horizontal;
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -moz-flex;
  display: -webkit-flex;
  display: flex;
  
  -webkit-justify-content: space-around;
  justify-content: space-around;
  -webkit-flex-flow: row wrap;
  flex-flow: row wrap;
  -webkit-align-items: stretch;
  align-items: stretch;
}

.header,
.footer  { flex: 1 100%; }
.sidebar { flex: 1; }
.main    { flex: 2; }

.flex-item {
  
  background: tomato;
  padding: 10px;
  width: 100px;
  border: 3px solid rgba(0,0,0,.2);
  
  color: white;
  font-weight: bold;
  font-size: 2em;
  text-align: center;
}
</style>
</head>
<body>
<ul class="flex-container">
  <li class="flex-item header">Header</li>
  <li class="flex-item sidebar">Sidebar</li>
  <li class="flex-item main">Main</li>
  <li class="flex-item sidebar">Sidebar</li>
  <li class="flex-item footer">Footer</li>
</ul>
</body>
</html>

Click to view the demo