0

我有两个 div 一个在另一个里面。我已经为两个 div 设置了一些边框,并且我希望两个 div 在水平和垂直方向上都位于页面的中心。我已经看到了类似问题的解决方案,但无法解决我的问题。还请分享好的资源,我可以从中了解定位,即相对绝对深度。

下面是我的 HTML 代码:

<!DOCTYPE html>
<style type="text/css">
    .outer {
        color:black;
        width: 400px;
        height:400px;
        border: 100px solid;
        border-radius:100%;
        border-color: red blue green yellow;
        position: static;
        margin: auto  auto auto auto;
        top:50%;
    }
    .inner{
        color:black;
        width: 100px;
        height:100px;
        border: 50px solid;
        border-radius:100%;
        border-color: red transparent green transparent;
        position: relative;
        top:50%;
        margin: -50px auto auto auto;
    }
</style>
<html>
    <body>
        <div class="outer">
            <div class="inner">
            </div>
        </div>
    </body>
</html>
4

4 回答 4

1

如果你知道两个盒子的大小,并且它们不会改变,你可以使用这个:

.outer {
  color:black;
  width: 400px;
  height:400px;
  border: 10px solid;
  border-color: red blue green yellow;
  position: absolute;
  margin: -200px  auto auto -200px;
  top:50%;
  left: 50%;
}
.inner{
  color:black;
  width: 100px;
  height:100px;
  border: 5px solid;
  border-color: red transparent green transparent;
  position: absolute;
  top:50%;
  left: 50%;
  margin: -50px auto auto -50px;
}​

注意我取出了边框半径并缩小了边框大小以使点更清晰。

基本上,您可以使用具有相对单位 (%) 的绝对定位,但使用固定的负边距,即框大小的一半。

见 JS 小提琴

于 2012-06-26T13:52:33.760 回答
1

大多数时候水平居中并不是什么大问题。margin: 0 auto样式添加到 adiv将主要执行您想要的操作。

然而,垂直居中似乎有点复杂。此处列出了 6 个垂直居中选项:http ://www.vanseodesign.com/css/vertical-centering/

另请注意该文章中的其他资源部分,其中还列出了一些很好的参考资料。

于 2012-06-26T13:53:58.333 回答
0

您的 div的实际height&width是 200px,包括borders. 因此,在您的内部,您将左和上边距设置为actual size/2

.inner{
  ...
  top: 50%;
  left: 50%;
  margin: -100px 0 0 -100px;


}
于 2012-06-26T14:02:00.713 回答
0

将 div 对齐到页面中心的一种聪明方法是使用 display:table 和 display:table-cell 方法。

HTML:

<div class="wrapper"> 
<div class="box"> 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc quis pretium arcu, eget semper lacus. Aliquam aliquam, augue non bibendum pretium, felis neque eleifend tortor, ut luctus mi ante vel nisl. Mauris id enim elit.
</p> 
</div> 
</div>

CSS:

html,body{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;}

.wrapper {
display: table-cell;
text-align: center;
vertical-align: middle;
}

.box {
background-color: red;
display: inline-block;
text-align: center;
padding:10px;
width: 100px;
height:auto;
}

观看现场演示:

http://jsfiddle.net/Narppavi/ej6yL/

于 2014-03-17T10:05:09.587 回答