将div放在相对于页面的居中div的位置

时间:2013-03-01 10:43:38

标签: jquery css3 html position relative

尝试将红色div放置在靠近中心div的位置,如下图所示:
你能建议我使用css3或jquery方法吗?

橙色div通过样式居中:{margin-left和margin-right auto} 我想要红色div总是接近红色div 以及红色div TOP位置应该固定在它的位置。相对于橙色div。 (相对于webexplorer)


enter image description here

2 个答案:

答案 0 :(得分:1)

在这种情况下不需要CSS3,如果您知道红色div的尺寸,则可以执行以下操作(如此JSBin所示):

.orange {

  background-color: orange;
  margin: 0 auto;
  width:  200px;
  height: 200px;
  position: relative;

}

.red {

  background-color: red;
  position: absolute;
  top: 0;
  left: -50px;
  width: 50px;
  height: 50px;

}

如果你不知道元素的维度,那么情况就会变得有点棘手,因为子元素不会溢出它的父元素,因此维度总是最大的红色div维度。在这种情况下,您将需要稍微修改CSS并添加一些jQuery魔法,就像在其他JSBin中演示的那样。

CSS

orange {

  background-color: orange;
  margin: 0 auto;
  width:  200px;
  height: 200px;
  position: static;

}

.red {

  background-color: red;
  position: relative;

的Javascript

jQuery(document).ready(function($){

  var redWidth = $('.red').width();
  $('.red').css('left', -redWidth);

});

更新

既然您更新了问题,那么答案也需要更新:我能想到这个解决方案(您可以看到它正常工作here):

$(window).scroll(function(){

    $('.red').css('top', window.pageYOffset);

});

但也许有一个更好的CSS解决方案。

更新#2

好的,只有当您知道居中容器的宽度时,才能找到更优雅,仅限CSS的解决方案。听到这个(并看到它in action):

.red {

  background-color: red;
  margin-left: -150px; // See note (1)
  position: fixed;
  top: 0;
  left: 50%;
  width: 50px;
  height: 50px;

}

(1)此边距是通过将橙色元素的width减半并添加红色的width来计算的。如果您不知道红色的宽度,请使用上面 Javascript 部分中介绍的技巧。

答案 1 :(得分:0)

只要知道红色块的尺寸,就可以将它放在橙色块内,并将其绝对定位到左边的宽度像素:

请参阅demo

CSS:

.container {
    position: relative;
    background-color: #FFCE6B;
    width: 700px;
    height: 300px;
}

.orangeblock {
    position: relative;
    margin: 0 auto;
    background-color: orange;
    width: 300px;
    height: 200px;
}

.redblock {
    position: absolute;
    left: -100px;
    background-color: red;
    width: 100px;
    height: 100px;
}

标记:

<div class="container">
    <div class="orangeblock">
        <div class="redblock"></div>
    </div>
</div>

如果知道红色块的尺寸,那么你仍然可以将它放在橙色块内并通过jQuery进行定位:

$(document).ready(function() {
    $(".redblock").css({position: "absolute", left: -$(".redblock").outerWidth()})
});
相关问题