[英]How can I have a fixed div next to a parent div?
I'm trying to get a div with a button next to a parent div. 我正在尝试在父div旁边添加一个带按钮的div。 Like this: 像这样:
____________
|relative |
| |
| |
| |_______
| | fixed |
| |_______|
| |
| |
|__________|
The fixed div has to be fixed during scrolling but at all time next to the parent and not under or above its parent. 固定div必须在滚动期间固定,但始终固定在父级旁边,而不是在父级之下或之上。
How can I accomplish this? 我该怎么做?
Use position:fixed
for the second div 使用position:fixed
于第二格
HTML HTML
<div class="main">
zx
</div>
<div class="fix">
<button>Click</button>
</div>
CSS CSS
html, body{
height:100%;
margin:0
}
.main{
height:100%;
width:50%;
background:grey;
}
.fix{
position:fixed;
top:50%;
border:red solid 2px;
background:yellow;
left:50%
}
Your main problem is that the element with position: fixed
is always relative to the body. 您的主要问题是position: fixed
的元素始终相对于身体。 It behaves differently from elements with position: absolute
, which is relative to parent element with position: relative
declared. 它的行为与具有position: absolute
元素的行为不同,后者相对于具有position: relative
声明的父元素。
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. 因此,主要问题是,如果将left
设置为fixed元素,则即使它的父元素相对放置,它也会粘贴到body元素的左边缘。 But you could use a trick, and skip left
declaration for fixed element. 但是您可以使用技巧,并跳过固定元素的left
声明。
.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>
Here's a JSFiddle example 这是一个JSFiddle示例
you're looking for position: absolute
, not fixed -- if your parent has the class parent
and the button has the class button
, what you need is similar to (assuming button has a fixed width of 100px for this): 您正在寻找position: absolute
,不固定-如果您的父级具有class parent
级,而按钮具有class button
,则您需要的类似于(假设按钮的固定宽度为100px):
.parent { position: relative; }
.button { position: absolute; top: 45%; right: -100px; }
here's an example fiddle (added some width/heights to demonstrate, these should come from your content instead) http://jsfiddle.net/WpnP4/ 这是一个示例小提琴(添加了一些宽度/高度来演示,这些宽度/高度应该来自您的内容) http://jsfiddle.net/WpnP4/
Edit: just realized the question is not 100% clear -- I assumed you wanted the button to be next to a specific element and scroll with the screen. 编辑:刚刚意识到问题不是100%清楚-我以为您希望按钮位于特定元素旁边并在屏幕上滚动。 Use position:fixed
if you want the button element to stay fixed in the screen. 如果希望按钮元素在屏幕中保持固定,请使用position:fixed
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.