fixed position div inside div container

2020-04-03 10:20发布

I am trying to create fixed position div inside relative container. I am using bootstrap css framework. I am trying to create a fixed position cart. So whenever user scroll page it will show cart contents. but now problem is, it ran outside that container div.

This has to work in responsive mode.

Here my try:

<div class="wrapper">
    <div class="container">
        <div class="element">
            fixed
        </div>
    </div>
</div>

CSS Code:

.wrapper {
    width:100%
}
.container {
    width:300px;
    margin:0 auto;
    height:500px;
    background:#ccc;
}
.element {
    background:#f2f2f2;
    position:fixed;
    width:50px;
    height:70px;
    top:50px;
    right:0px;
    border:1px solid #d6d6d6;
}

See live example here.

9条回答
不美不萌又怎样
2楼-- · 2020-04-03 10:49
<div style="position: fixed;bottom: 0;width: 100%;">
  <div class="container" style="position: relative;">
    <div style="position: absolute;right: 40px;bottom: 40px;background:#6cb975;border-radius: 50%;width: 40px;text-align: center;height: 50px;color: #fff;line-height: 50px;">
      F
    </div>
  </div>
</div>
查看更多
smile是对你的礼貌
3楼-- · 2020-04-03 10:52

Yes, you can do it, just use margin-top property instead of top property.

When you use position: fixed and specify a top and or left position, you'll find that the element will be fixed relative to the window, and not to any other element of position: relative.

There is a way around this and that is not to specify top and left positions but instead to use margin-left and margin-top on the position: fixed element.

Source: https://www.gravitywell.co.uk/latest/design/posts/css-tip-fixed-positioning-inside-a-relative-container/

查看更多
甜甜的少女心
4楼-- · 2020-04-03 10:52

You can just add

.element {
    left:368px;
}

Fiddle: http://jsfiddle.net/UUgG4/

查看更多
登录 后发表回答