Nowadays, CSS flexbox has been widely use for front-end web developing; It is currently supported on major browsers such as Google Chrome, Firefox and etc. Thus a simple example below will help you understand how CSS Flexbox works in an easy way unlike years passed by.

As a web developer especially beginner, to center an HTML element, block, image and or content has been so far easy today; thanks to CSS Flexbox by the way.

Without further a do, details are as follows;

HTML CODE

Step 1: Copy and paste this HTML code on your index.html or index.php file.
<div class="container">
  <div class="item">
      <!--Put an image here--!>
  </div>
  <div class="item">
    <p>This is a sample text</p>
  </div>
</div>


CSS CODE

Step 2: Copy and paste this CSS code below on your CSS file to see the result.
body{
  box-sizing:border-box;
  margin:2em;
}
.container{
  height:600px;
  padding:1em;
  border:1px solid #eee;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  justify-content:space-evenly;
  align-items:center;
}
.item{
  height:300px;
  background-color:#eee;
  padding:5em;
  width:300px;
  display:flex;
  align-items:center;
}


Brief Summary:

Class (.container) above is the parent element or the flex container.
Class (.item) above is the child element or flex items (text & image).

  • The above example shows that, a parent is responsible in centering the flex items.
  • By setting (display:flex) property, flex container becomes flexible.
  • (Justify-content:center) aligns the flex items at the center of the container
  • (align-items:center) aligns the flex items in the middle of the container.

As you can see, I also use the (display:flex) and (align-items:center) properties to flex items to vertically and horizontally align an image in the center.


Note:

- Both Flex container and Flex items can use flexbox properties for more flexibility.
- To see the exact result I have provided a codepen snippet link below.
https://codepen.io/bloggersPh/pen/yLBvYyp

Post a Comment

Previous Post Next Post