我如何在父div旁边有一个固定的div? [英] How can I have a fixed div next to a parent div?

查看:89
本文介绍了我如何在父div旁边有一个固定的div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在父div旁边创建一个带按钮的div.像这样:

I'm trying to get a div with a button next to a parent div. Like this:

____________
|relative  |
|          |
|          |
|          |_______
|          | fixed |
|          |_______|
|          |
|          |
|__________|

固定div必须在滚动期间固定,但始终固定在父级旁边,而不是在父级之下或之上.

The fixed div has to be fixed during scrolling but at all time next to the parent and not under or above its parent.

我该怎么做?

推荐答案

您的主要问题是,带有position: fixed的元素总是相对于主体.它的行为与带有position: absolute的元素不同,后者相对于声明了position: relative的父元素.

Your main problem is that the element with position: fixed is always relative to the body. It behaves differently from elements with position: absolute, which is relative to parent element with position: relative declared.

所以主要的问题是,如果将left设置为固定元素,即使其父元素相对放置,它也会粘贴到body元素的左边缘. 但是,您可以使用技巧,并跳过固定元素的left声明.

So the main problem is, that if you set left to the fixed element, it sticks to left edge of body element, even if it's parent is positioned relative. But you could use a trick, and skip left declaration for fixed element.

.main {
    /*just for visualisation*/
    width: 300px;
    height: 1500px;
    background: #ccc;
}
.main, .fake-wrapper {
    float: left;
}
.fixed {
    position: fixed;
    top: 50%;
}

<div class="main">
<!-- your content -->
</div>
<div class="fake-wrapper">
    <div class="fixed">
        <a href="/">click!</a>
    </div>
</div>

这是一个 JSFiddle示例

这篇关于我如何在父div旁边有一个固定的div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆