固定父div旁边的div [英] Fixed div next to parent 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.
也许有人知道这个问题的解决方案。请让我知道。
Maybe someone knowes a solution to this problem. Please let me know.
推荐答案
我想我可能有一个解决方案。主要问题是, position:fixed
的元素总是相对于body。它与具有 position:absolute
的元素的行为不同,后者是相对于父元素的 positiono:relatvie
声明的。
I think i might have a solution for you. Main problem is, that element with position: fixed
is always relative to body. It behaves differently from element with position: absolute
, which is relative to parent element with positiono: relatvie
declared.
所以主要的问题是,如果你将 left
设置为fixed元素, body元素,即使它的父对象是相对的。 但可以使用一个技巧,并跳过 left
声明的固定元素。让我们说这是你的html:
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. Let's say this is your html:
<div class="main">
<!-- your content -->
</div>
<div class="fake-wrapper">
<div class="fixed">
<a href="/">click!</a>
</div>
</div>
这应该是你的css:
.main {
/*just for visualisation*/
width: 300px;
height: 1500px;
background: #ccc;
}
.main,
.fake-wrapper {
float: left;
}
.fixed {
position: fixed;
top: 50%;
}
这是一个工作示例: jsFiddle示例
这篇关于固定父div旁边的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!