There is HTML:

<body> <div class="container" > Контейнер </div> </body> 

How to align the .container block in the center of <body> regardless of the width of the page?

  • 2
    margin: 0 auto; - HamSter
  • @HamSter, I also answered at the beginning, but the question says: on the center of the page . That is, not only along the X axis , but also along the Y axis . - Acne Black
  • @ Vitaly Black, "regardless of the width of the page" usually means horizontally. - HamSter

4 answers 4

You can use Grid Layout or Flex Layout , but first make sure that the customer’s requirement allows using these technologies. There is a good site for this: Can I use .... Good luck!

Here's a sandbox for Flex;

UPD : Fixed an example. I thought that you just need to center the element on the axis: X. If, however, you just need to center the element: container along the axis: X , then set the properties: margin: 0 auto; and write down your width, because it is a block element, and it occupies the entire width of the entire allowable space.

 .page { height: 100vh; display: flex; align-items: center; justify-content: center; } .container { background: #000; width: 30%; color: #fff; } 
 <body class="page"> <div class="container">Lorem</div> </body> 

     html{ height: 100%; } body{ display: flex; justify-content: center; align-items: center; height: 100%; } .container{ width: 50vw; height: 50vh; background: red; } 
     <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div class="container"></div> </body> </html> 

      Using flex in css

      align-items: center vertically

      justify-content: center horizontally

       .body { height: 180px; display: flex; align-items: center; justify-content: center; } 
       <body class='body'> <div class="container" > Контейнер </div> </body> 

        margin: 0 auto; - automatic external padding horizontally.

         body {margin: 0; background: #ddd;} .container {display: block; width: 70%; height: 100vh; margin: 0 auto; background: #aaa;} 
         <body> <div class="container"> Контейнер </div> </body>