2012-10-20 79 views
1

我的外部div是位置:相对和内部div是绝对定位的。顶部和底部定位与自动?

我想设置我的内部div中心垂直对齐,并思考使用top:auto和bottom:auto但它不工作。请告诉我如何做到这一点。

 div.Container div.Right 
    { 
      width:50%; 
      float:right ; 
      border: 01px dashed green; 
      height:95px !important;  
      position:relative !important; 
    } 

    div.header-search 
    {  
     overflow:auto; 
     display:inline;  
     border:0px dashed blue;   
     position:absolute; 
     top:auto; 
     bottom:auto; 
     right:0px; 
    } 



<div class="Right"> 
      <div class="header-search"> 
       <input type="text" class="searchbox" /> 
       <input type="button" class="searchbutton" value="›" /> 
      </div> 
</div> 

回答

-1

尝试将内部div设置为margin:auto 0;

+0

这适用于固定宽度的水平居中元素,但不适用于垂直居中的东西 – Luca

0

要达到目标的最佳方法是删除bottom:auto;样式并用top:50%;替换top:auto;。之后,找出你试图居中的搜索栏的高度(比如说20px),并在其高度的一半添加一个负边距样式,因此如果它是20px,则样式为margin-top:-10px;

你的CSS会是这样的:

div.header-search 
{  
    overflow:auto; 
    display:inline;  
    border:0px dashed blue;   
    position:absolute; 
    top:50%; 
height:20px; 
margin-top:-10px; 
right:0; 

}​ 
+0

我的示例中的小提琴在这里:http://jsfiddle.net/xTsXM/ – JamieM23

0

集.header搜索顶部:50%或底部:50%,则使用的margin-top :-(DIV高度的一半)或DIV高度的下边距一半:-();分别。我有时也只是简单地使用top:50%或bottom:50%而没有负边距。

例如:

div.header-search 
    {  
     overflow:auto; 
     display:inline;  
     border:0px dashed blue;   
     position:absolute; 
     top:50%; 
     height: 500px; 
     margin-top:-250px; 
     right:0px; 
    } 

所以是的,在这种情况下,你必须设置一个固定的高度。

+0

与jamie's – LazerSharks

1

您可以在内部DIV像这样使用line-height:95px;外股利和vertical-align: middle;

div.Right 
{ 
    width:50%; 
    float:right ; 
    border: 01px dashed green; 
    line-height:95px !important; 
    display: block; 
} 

div.header-search 
{  
    overflow:auto; 
    border:0px dashed blue;  
    vertical-align: middle; 
} 

你可以在这里发挥它:http://jsfiddle.net/leniel/5Mm67/


如果你想为水平对齐内部div的内容,只需在div.Right中加入:

text-align: center;

这里的结果:http://jsfiddle.net/leniel/5Mm67/1/

0

设置在div绝对位置: “顶部:50%;”

它会显示一个小点到低点(顶点od绝对div应该在父高度的50% - 相对格)上,但有很多方法可以解决这个问题。

例如: 甚至还有一个div与位置相关,并将其移动到绝对div高度的一半(这在代码中看起来不太好) - 您必须知道div的高度,如果您不能测量像jQuery一样的大小和移动div litle更高。

最简单的方法:也许尝试45%而不是50%(如果它不像素到像素设计)。

Propably有人有更好的解决方案,如果这样我想看到他们:)

0

这应该工作:

div.header-search 
{  
    overflow:auto; 
    display:inline;  
    border:0px dashed blue;   
    position:absolute; 
    top:50%; 
    right:0px; 
} 
0

枝,有几种方法来格的垂直中心通过其完成CSS的魔力....这里是例子,它工作正常,我已经测试...并且它工作正常。

HTML:

<div id="parent"> 
    <div id="child">Content here</div> 
</div> 

CSS:

#parent {position: relative;} 

#child { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    height: 30%; 
    width: 50%; 
    margin: -15% 0 0 -25%; 
} 

这是其他方法click here to see complete reference 希望,它会帮助你。干杯。 !