如何让div居中对齐?

Fre*_*red 8 css

我想要一个垂直和水平居中的 div,即位于页面的中心。我尝试了position:absolute并将div的右上角左下角设置为0!但问题是,当我放大页面时,它与其他标题和其他 div 重叠!请帮我!如何在放大页面时将 div 定位在页面中心而不与其他 div 重叠?

就像我尝试过的那样:

.center{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
 }
Run Code Online (Sandbox Code Playgroud)

Has*_*ash 7

尝试,

html{
  height:100%;
}
body
{ height:100%;
  background-color: #fcfcfc;

}
.center
{
  position: absolute;
  margin: auto;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  width: 100px;
  height: 100px;
  background-color: #ccc;
  border-radius: 3px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="center"></div>
Run Code Online (Sandbox Code Playgroud)


ter*_*eah 4

html, body {
  height:100%;
}

.center {
  border: 2px solid blue;
  margin: auto;
  position: relative;
  text-align: center;
  top: 50%;
  width: 20%;  
}
Run Code Online (Sandbox Code Playgroud)
<div class="center">
  <p>Test Text</p>
</div>
Run Code Online (Sandbox Code Playgroud)