How to align flexbox container into center using JavaScript?


To align a flexbox container into the center using JavaScript, we first need to select the container using a DOM manipulation method such as querySelector. Next, we need to set the container's CSS properties to "display: flex" and "justify-content: center". This will align the items within the container to the center horizontally.

Flexbox is a layout mode in CSS3 that lets you align and distribute elements on a page. It can be used for things like creating a main navigation bar or laying out a photo gallery. Flexbox is a powerful tool that can make your web layouts more flexible and responsive.

Approach

There are several ways to center a flexbox container using JavaScript −

  • The most common approach is to set the margin-left and margin-right properties to ‘auto’. This will cause the flexbox container to be centered within its parent element.

  • Another approach is to set the width of the flexbox container to ‘100%’ and then set the ‘justify-content’ property to ‘center’. This will cause the flexbox container to be centered within its parent element.

The code below will center a flexbox container using JavaScript. The container must have a defined width, and the flex-direction must be set to row.

First, we get the element with the ID of “container” −

var container = document.getElementById("container");

Then, we set the container’s style.flexDirection to “row” −

container.style.flexDirection = "row";

Finally, we set the container’s style.justifyContent to “center” −

container.style.justifyContent = "center";

Example

<!DOCTYPE html>
<html>
<head>
   <title>Align Flexbox Container</title>
</head>
   <body>
      <div id='container'>
         <div style="color: black;">I will be centered</div>
      </div>
      <script> 
         var container = document.getElementById("container");
         container.style.display ='flex';
         container.style.flexDirection = 'row';
         container.style.justifyContent = 'center';
      </script>
   </body>
</html>

Updated on: 13-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements