如何将 div 居中对齐到页面中间?

8
我希望有一个div可以垂直和水平居中,即在页面的中心。我尝试使用position: absolute并将div的top、right、bottom、left设置为0!但问题是当我放大页面时它会与其他标题和div重叠!请帮助我!如何在不重叠其他div的情况下将div定位在页面中心?
就像我尝试过的:
.center{
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
 }

1
尝试将边距设置为 auto - Rishabh Mishra
哎呀!我忘记在代码中提到margin: auto了。我已经尝试过了,但仍然不起作用。 - Fred
1
请尝试一下...https://jsfiddle.net/DChandraShekhar/8a7L8dtv/1/ - Chandra Shekhar
7个回答

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;
}
<div class="center"></div>


4

html, body {
  height:100%;
}

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


2
使用 margin: auto 可以实现水平居中块级元素(如 div)。

.center {
    margin: auto;
    width: 60%;
    border: 3px solid #73AD21;
    padding: 10px;
}
<div class="center">
  <p><b>Note: </b>Using margin:auto will not work in IE8, unless a !DOCTYPE is declared.</p>
</div>


2

Flex是最好的解决方案,完美的位置。

如果您想要用于加载器,请使用固定位置的全尺寸div,并使用flex来设置div内容。

Flex指南 https://css-tricks.com/snippets/css/a-guide-to-flexbox/

body, html {
  height:100%
}

body {
  display:flex;
  margin:0;
  flex-direction:column;
}

.mydiv {
  margin:auto;
}
<div class="mydiv">test</div>


我也认为flex是这个问题的最佳解决方案。只需注意一些旧浏览器-它们可能需要另一种解决方案。您可能不应该在body上使用flex,以避免影响页面上的所有其他元素。相反,将其用于包围要居中的div的包装器div上。像<div class="wrapper"> <div class="mydiv">test</div></div> 给包装器100%的宽度和高度,并根据需要设置固定或绝对位置。 - Ina
那还是不行!当缩放页面时,该div仍会与其他元素重叠!我想让它保持在原位。 - Fred

1

试一下

HTML

<div class="center">
  Lorem ipsum dolor sit amet, 
</div>

CSS

html,body{
  height:100%;
}
.center{
  position: relative;
  top:50%;
  left:50%; 
}

参考链接

希望这有所帮助。


1
2020年4月23日,从真实项目中复制。
    html, body {
        display:flex;
        height: 100%;
        width: 100%;
        margin: 0;
    }


<div id="id01" style="width: 50%;height: 30%;background-color: red; margin: auto;">
</div>

0

这是您的HTML主体
<div class="testbox"> <!-- 您的div主体 --> </div>

这是您的CSS
.testbox { width: 800px; margin: 0 auto; position: absolute; top: 0; bottom: 0; left: 0; right: 0; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接