div内部div的垂直和水平对齐

时间:2012-06-26 13:43:52

标签: css

我在另一个里面有两个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 个答案:

答案 0 :(得分:1)

IF 你知道两个盒子的大小,而且不会更改,你可以使用它:

.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;
}​

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

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

See the JS Fiddle

答案 1 :(得分:1)

水平居中大部分时间都不是问题。将margin: 0 auto样式添加到div将主要执行您想要的操作。

然而,

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

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

答案 2 :(得分:0)

实际height&amp;你的div的width是200px,包括borders。因此,在你的内心,你将设置左和右;最高保证金为actual size/2

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


}

答案 3 :(得分:0)

将div与页面中心对齐的一种智能方法是使用display:table和display:table-cell method。

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/