0

This is a simplified version of a more complex problem. Suppose there are two divs within the body, which have to be vertically centered. Because of some other requirements DOM can't change. So only by changing css I need to vertically align them center. I have tried many other stackoverflow posts but so far couldn't make it work.

Here is my code:

<!DOCTYPE html>
<html>
<head>
<style>

body{

}
.div1{
    display: block;
    background: red;
    width: 300px;
}
.div2{
    display: block;
    background: green;
    width: 300px;

}
</style>
</head>
<body>

    <div class="div1">
        <p>This is div1</p>
    </div>
    <div class="div2">
        <p>This is div2</p>
    </div>

</body>
</html>
apadana
  • 13,456
  • 15
  • 82
  • 98

1 Answers1

1

This is possible using flexbox.

html,
body {
  height: 100%;
}

body {  
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

See this CodePen

hotmeteor
  • 495
  • 6
  • 7