Setting a Fixed Width for Items in CSS Flexbox


Syntax

The syntax of CSS flex property is as follows −

Selector {
   flex: /*value*/
}

Example

The following examples illustrate CSS flex property.

 Live Demo

<!DOCTYPE html>
<html>
   <head>
      <style>
         div {
            display: flex;
            padding: 4%;
         }
         .d1 {
            background: hotpink;
            flex: 0 20 20px;
         }
         .d2 {
            background: greenyellow;
            flex: 1;
         }
         .d3 {
            background: tomato;
            flex: 1;
         }
      </style>
   </head>
   <body>
      <div class="demo">
         <div class="d1"></div>
         <div class="d2"></div>
         <div class="d3"></div>
      </div>
   </body>
</html>

This gives the following output

Example

 Live Demo

<!DOCTYPE html>
<html>
   <style>
      div {
         display: flex;
         border-radius: 2%;
         background-color: linen;
         height: 50px;
      }
      #d1 {
         border: 5px solid orangered;
         padding: 2%;
         flex: auto;
      }
      #d2 {
         border: 5px groove greenyellow;
         width: 66px;
      }
      #d3 {
         padding: 5%;
         border: 5px ridge hotpink;
      }
      #d4 {
         height: 100px;
         border: 5px solid magenta;
      }
   </style>
   <body>
      <div>
         <div id="d1">Auto Resize</div>
         <div id="d2">66px fixed width</div>
         <div id="d3"></div>
      </div>
      <div id="d4">Last Div</div>
   </body>
</html>

This gives the following output

Updated on: 10-Feb-2021

838 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements