JSFiddle - React, Tailwind, and code Playground

by Bryan Braun

HTML

<p>position absolute centering (with pseudo elements)</p>
<div id="parent1">
  <div id="child1">
    test
  </div>
</div>

<hr />
<p>flexbox centering (w margins)</p>
<div id="parent2">
  <div id="child2">
    test
  </div>
</div>

<hr />
<p>flexbox centering (w extra div)</p>
<div id="parent3">
  <div id="child3">
    <div id="subchild3">
      test
    </div>
  </div>
</div>

<hr />

<p>grid centering</p>
<div id="parent4">
  <div id="child4">
    test
  </div>
</div>

<hr />

CSS

#parent1 {
  position: relative;
  border: 3px solid dodgerblue;
  width: 300px;
  height: 180px;
  overflow: auto;
}

#child1 {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  margin: auto;
  background: green;
  width: 200px;
  height: 200px;
}
#child1::before {
  content: "";
  display: block;
  position: absolute;
  top: -3rem;
  left: 0;
  width: 1px;
  height: 3rem;
}
#child1::after {
  content: "";
  display: block;
  position: absolute;
  bottom: -3rem;
  left: 0;
  width: 1px;
  height: 3rem;
}

/****************/

#parent2 {
  border: 3px solid dodgerblue;
  width: 300px;
  height: 180px;
  box-sizing: border-box;
  overflow: auto;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

#child2 {
  background: green;
  flex: 0 0 200px;
  height: 200px;
  margin: auto;
}

/****************/

#parent3 {
  border: 3px solid dodgerblue;
  width: 300px;
  height: 180px;
  overflow: auto;
  
  display: flex;
  align-items: center;
  justify-content: center;
}

#child3 {
  background: green;
  flex: 0 0 200px;
  height: calc(200px + 3rem + 3rem);
  margin: auto;
  padding: 3rem 0;
  box-sizing: border-box;
}

#subchild3 {
  background: darkgreen;
  width: 100%;
  height: 100%;
}

/****************/

#parent4 {
  border: 3px solid dodgerblue;
  width: 300px;
  height: 180px;
  box-sizing: border-box;
  overflow: auto;
  
  display: grid;
  align-content: center;
  justify-content: center;
}

#child4 {
  background: green;
  height: 200px;
  margin: auto;
}