How to properly place an HTML element horizontally and vertically center?

Photo by Christopher Gower on Unsplash

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

<div class="container">
     <div class="item">
       <!--Put an image here--!>
     </div>
     <div class="item">
       <p>This is a sample text</p>
     </div>
</div>code-box

CSS Code

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;
}code-box

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.alert-info

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.alert-info

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.alert-info

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

Much appreciated for gently taking so much personal time to respectfully submit a published comment on BloggersPh. If you sincerely want to submit some ethical questions, I will be delighted to respond appropriately them here or via private email. Please do not submit a mean or disrespectful comment; they will be eradicated. Enjoy!

Previous Post Next Post