How to push element in the center of the container in CSS3?

ยท

0 min read

There may be multiple ways but I will explain 4 here

Let suppose parent container had a class name 'box' and child had a 'small-box'

  1. With Translate

       .box{ 
                 position: relative;
                 width: 500px;
                 height: 500px;
              }
       .small-box{
                           position: absolute;
                           top: 50%;
                           left: 50%;
                           transform: translate(-50%, -50%);
                       }
    
  2. With flexbox

         .box{
                  display: flex;
                  flex-direction: column;
                  justify-content: center;
                  align-items: center;
               }
  1. With grid

    It would work as same as flexbox.
    
      .box{
               display: grid, 
                justify-content: center;
                align-items: center;
    }
    
  2. With margin

              .box{
                       width: 500px;
                       height: 500px;
                    }
              .small-box{
                                with: 20px;
                                height: 20px;
                                margin: auto;
                       }
    

    1,2,3 are work but sometimes 4 would not work. So don't ๐Ÿ˜ฉ. If you found something wrong please correct me. If you know other than these techniques please let us know. Thanks for reading