Sunday, January 30, 2022

CSS flex usage note

Flex can be used to solve most ui layout requirements in regular business applications if each items need to have equal height. 

Flex consists of flex container and flex items, each of them supports different css styles. It is important to understand which css style works on flex container or flex items.

Flex container:

For any container html element, when setting the below css style to it, the element becomes a flex container, and any direct sub elements become flex items.

.myform {

  display: flex;

}

The flex container has the below css styles:

.myform {

  display: flex;

  flex-wrap: wrap;  //control whether wrap the elements when page shrinks

 justify-content: center; // control where to shall all flex item in flex container in main axis: center, flex-start, flex-end, space-around, space-between

align-items: stretch; // control how each flex item is aligned in cross axis direction: stretch, flex-start, flex-end, center and baseline

align-content: normal: //control how all flex items are align in flex container in cross axis direction, not used very often.

}


Flex elements

Any direct sub elements of flex container element can be styled by flex item css styles. The styles controls the element itself and its sibling elements' behavior. The styles include:

flex: define how the element will grow or shrink when the page width changes. It can be used to define how item grows and shrinks related to other elements. For example, a growing input text box with a button with default width can be defined as below

   input[type="text"] {

      flex: 1 0 auto

  }

  button[type="submit"] {

    flex: initial 0 initial

  }


Sample usage 1

A growing field and a fix width item, the growing field occupies all remaining line

  .search-form {
    display: flex;
    flex-wrap: wrap;
  }
  growingitem {
    flex: 1 0 auto
  }
 fixeditem {
    flex: initial 0 initial
  }


Sample usage 2

Two fields occupy left and right end of the line by setting justify-content: space-between

  .search-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }
  input[type="search"] {
    flex: 1 0 initial
  }
  button[type="submit"] {
    flex: 1 0 initial
  }

Expanding item to occupy all its container's space 
When setting the below display style to any item within a container, the item becomes a flex container, and by default, flex container will expend and stretch to all available space in container.  
display: flex

No comments:

Post a Comment