如何在同一时间页面中将div粘贴到顶部?

时间:2014-06-09 17:42:12

标签: html css

我有一个固定高度和宽度的div,我使用左右auto边距居中。但我想在整个页面中看到这个栏,以便我使用position:absolute粘贴它。但随后酒吧左转并且不再居中。如何将杆固定在中心顶部位置?

<div class="bar">bar</div>

.bar{
    width: 400px;
    height: 40px;
    margin-left:auto;
    margin-right:auto;
    background-color:orange;
}

Here是小提琴。

7 个答案:

答案 0 :(得分:2)

尝试使用100%宽度的容器div,将其固定到顶部,然后将栏放在其中心。 CSS:

.bar{
    width: 400px;
    height: 40px;
    margin:0 auto;
    background-color:orange;
}
.container
{
width:100%;
    position:fixed;
    top:0px;
    left:0px;
}

Updated Fiddle

答案 1 :(得分:1)

http://jsfiddle.net/hkZju/12/

.bar{
    width: 400px;
    height: 40px;
    top:0;
    left:50%;
   margin-left:-200px;
    background-color:orange;
    position:fixed;
}

答案 2 :(得分:0)

.bar{
width: 400px;
height: 40px;
left : 50%;
margin-left:-200px;
top : 0%;
position : absolute;
background-color:orange;
}

答案 3 :(得分:0)

因此,即使您滚动页面,该栏仍将保持在顶部,您必须使用position:fixed。然后,要使其居中,请将左侧设置为50%,将margin-left设置为减去宽度的一半。

.bar{
    width: 400px;
    height: 40px;
    position: fixed;
    top: 10px;
    left: 50%;
    margin-left: -200px;
    background-color:orange;
}

http://jsfiddle.net/hkZju/9/

答案 4 :(得分:0)

您需要将.bar置于包含position: absolutewidth: 100%

的div中

检查这个小提琴demo

.bar{
   position: absolute;
   width: 100%;
}

.bar div {
   width: 400px;
   height: 40px;
   margin-left:auto;
   margin-right:auto;
   background-color:orange;    
}

答案 5 :(得分:0)

我想添加:

position: fixed top right;

像TylerH说的那样,或者

position:absolute top right;

将是您最好的选择。更灵活。

固定为始终显示,绝对为&#34; pin&#34;到页面。

答案 6 :(得分:0)

你可以通过动态改变div的左边值来使用jquery来处理这个,下面是代码 -

$(document).ready(function(){
   $('.bar').css('left',($(document).width() - $('.bar').width())/2);
});

或者如果你想用css做 - 添加下面的css属性

.bar{
 left : 50%;
 margin-left:-200px;//should be half in the width of the div
}
相关问题