【问题标题】:attaching position a div to a centered div relative to page将 div 的位置附加到相对于页面的居中 div
【发布时间】:2013-03-01 10:43:38
【问题描述】:

尝试将附加的红色 div 放置在中心 div 附近,如下图所示:
你能给我推荐一个 css3 或 jquery 简单的方法吗?

橙色 div 通过样式居中:{margin-left 和 margin-right auto} 我只希望红色 div 始终靠近红色 div。
并且红色 div 顶部位置应该固定在它所在的位置。而不是相对于橙色 div。 (相对于 webexplorer)


【问题讨论】:

  • 我确实编辑了我的答案以实现您的愿望。

标签: jquery html css css-position


【解决方案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 部分中解释的技巧。

【讨论】:

  • 太棒了!谢谢你。精彩的答案!正是我要找的。你拯救了我的一天
【解决方案2】:

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

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()})
});

【讨论】:

  • 问题是这样的。我希望顶部位置是固定的(到 explorer.not 页面),所以如果页面滚动到底部,红色 div 应该保持原样。
  • @Mahn 实际上 jQuery 的解决方案并不是完全精确的:子红色块永远不会用这种布局溢出它的父维度,因此 (a) 要么将其父级拉伸到其尺寸,要么 (b) 将是父级固定尺寸。要解决此问题,请参阅我的答案。
  • @N.Ramos 我更新了我的答案以满足您使用 jQuery 的新要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
相关资源
最近更新 更多