Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

css - Position element fixed vertically, absolute horizontally

Here's what I'm trying to accomplish:

I need a button which is positioned a certain distance from the right side of a div, and is always that same distance from the side of the div no matter the size of the viewport, but will scroll with the window.

So it is x pixels from the right side of the div at all times, but y pixels from the top of the view port at all times.

Is this possible?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Position Fixed Element Horizontally Based Off Another Element

(Disclaimer Note: The solution offered here is not technically "absolute horizontally" as the question title stated, but did achieve what the OP originally wanted, the fixed position element to be 'X' distance from the right edge of another but fixed in its vertical scroll.)

I love these types of css challenges. As a proof of concept, yes, you can get what you desire. You may have to tweak some things for your needs, but here is some sample html and css that passed FireFox, IE8 and IE7 (IE6, of course, does not have position: fixed).

HTML:

<body>
  <div class="inflow">
    <div class="positioner"><!-- may not be needed: see notes below-->
      <div class="fixed"></div>
    </div>
  </div>
</body>

CSS (borders and all dimensions for demonstration):

div.inflow {
  width: 200px; 
  height: 1000px; 
  border: 1px solid blue; 
  float: right; 
  position: relative; 
  margin-right: 100px;
}
div.positioner {position: absolute; right: 0;} /*may not be needed: see below*/
div.fixed {
  width: 80px; 
  border: 1px solid red; 
  height: 100px; 
  position: fixed; 
  top: 60px; 
  margin-left: 15px;
}

The key is to not set the left or right at all for the horizontal on the div.fixed but use the two wrapper divs to set the horizontal position. The div.positioner is not needed if the div.inflow is a fixed width, as the left margin of the div.fixed can be set to known width of the container. However, if you desire than container to have a percentage width, then you will need the div.positioner to push the div.fixed to the right side of the div.inflow first.

Edit: As an interesting side note, when I set overflow: hidden (should one need to do that) on the div.inflow had no effect on the fixed position div being outside the other's boundaries. Apparently the fixed position is enough to take it out of the containing div's context for overflow.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...