How to center an element horizontally and vertically using flexbox in CSS

Arif Billah Babu

         

  CSS



Image not found!!

You can center an element horizontally and vertically using flexbox in CSS by applying a combination of flex container and flex item properties. Here's how you can do it:

HTML:

html
<div class="container"> <div class="centered-element"> <!-- Your content here --> </div> </div>

CSS:

css
.container { display: flex; justify-content: center; /* Center the child horizontally */ align-items: center; /* Center the child vertically */ height: 100vh; /* Set container height to full viewport height */ } .centered-element { /* Your centered element styles here */ }

Explanation:

  • .container is set as a flex container using display: flex;.
  • justify-content: center; aligns the flex items (in this case, the .centered-element) along the main axis (horizontal axis) of the flex container, effectively centering it horizontally.
  • align-items: center; aligns the flex items along the cross axis (vertical axis) of the flex container, effectively centering it vertically.
  • height: 100vh; sets the height of the container to be equal to the full viewport height, ensuring that the centered element is vertically centered within the viewport.

With this setup, the .centered-element will be both horizontally and vertically centered within the .container. Adjust the styles of .centered-element as needed for your specific design.