基于另一个divs高度居中div

时间:2012-07-10 17:18:14

标签: html css

我有一个外部div,在其中我有两个内部div来保存徽标和导航。我创建了这个小提琴http://jsfiddle.net/thiswolf/ZBMhr/1/

我希望导航设置基于徽标div来居中。这是html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Center Depending on another div</title>
  <style type="text/css">
  .container {
      margin-left:2%;
  }
  .outer {
      position:relative;
      height:100px;
      width:100%;
      background-color:orange;
  }
  .inner-left {
      position:relative;
      float:left;
      height:80%;
      width:200px;
      background-color:green;
      margin-top:10px;
      margin-bottom:10px;
  }
  .inner-right {
      position:relative;
      height:40%;
      width:auto;
      float:right;
      background-color:pink;
  }
  </style>
  <meta charset="uft-8">
</head>
<body>
   <div class="container">
      <div class="outer">
         <div class="inner-left">
            <h1>Logo</h1>
         </div>
         <div class="inner-right">
            <p>Navigation</p>
         </div>
      </div>
    </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

只要导航div高达40%,使用

margin-top: 30%;
position: absolute:
right: 0;

应该足够,因为40%+ 30%+ 30%等于全高。

当外部容器相对定位时,内部元素可以完全相对于父元素定位。

如果你想给元素一个固定的高度,你可以试试这个:

margin-top: 50%;
height: 40px;
top: -20px;

答案 1 :(得分:1)

使用css进行垂直居中有几种方法。对于这种情况,我建议采用负上边际方法。您将所需的元素定位为绝对值,顶部为50%,负上边距为高度的一半。

position:absolute;
top:50%;margin-top:-20%;//20 is half height in this case
right:0;//float doesn't apply to positioned elements

你可以在这里看到这个: http://jsfiddle.net/nAAJ7/1/