Home Html CSS Tutorial Center a Div Horizontally and Vertically in CSS

Center a Div Horizontally and Vertically in CSS

238
0

Center a Div Horizontally and Vertically in CSS

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Center a Div Horizontally and Vertically in CSS</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h2>Center a Div Horizontally and vertically in css</h2>
    <!-- center div with position -->
    <div class="box">
      <h2>Position</h2>
      <div class="absolute">
        <div class="inner-div"></div>
      </div>
    </div>

    <!-- center div with flexbox -->
    <div class="box">
      <h2>Flexbox</h2>
      <div class="flexbox">
        <div class="flexbox-inner-div"></div>
      </div>
    </div>

    <!-- center div with grid -->
    <div class="box">
      <h2>Grid</h2>
      <div class="grid">
        <div class="grid-inner-div">

        </div>
      </div>
    </div>
    
     
  </body>
</html>

CSS

body{
    margin: 0;
    padding: 0;
    text-align: center;
}

.box{

}


/* //////////////////////////////////////// */
/* Center with Position */
.absolute{
    background-color: aqua;
    width: 400px;
    height: 400px;
    margin: 0 auto;
    position: relative;
}

.inner-div{
    width: 200px;
    height: 200px;
    background-color: white;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

/* //////////////////////////////////////// */
/* Center with Flexbox */
.flexbox{
    background-color: green;
    margin: 0 auto;
    height: 400px;
    width: 400px;
    display: flex;
    justify-content: center;
    align-items: center;

}

.flexbox-inner-div{
    width: 200px;
    height: 200px;
    background-color: white;
}


/* //////////////////////////////////////// */
/* Center with Grid */
.grid{
    margin: 0 auto;
    width: 400px;
    height: 400px;
    background-color: indigo;
    display: grid;
    

}

.grid-inner-div{
    background-color: white;
    height: 200px;
    width: 200px;
    justify-self: center;
    align-self: center;
}

(Visited 95 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here