Reputation: 12512
I would like to position a div withing another element but make it stay in place when a page is scrolled vertically. The parent element is longer then the screen height. Can that be done with just CSS or do I need to use jQuery (that's what i normally use)? I'd use fixed position but am not sure how to associate it relative to the parent div...
<div id="veryHighDiv">
<div id="positionMe"></div>
</div>
So, I need it to be position relative to the parent in term of horizontal position, but "fixed" when it comes to vertical scroll.
Upvotes: 1
Views: 2564
Reputation: 47687
Quite simple with jQuery - http://jsfiddle.net/zA3mq/
$(window).scroll(function() {
$("#positionMe").css('position', 'fixed');
});
Upvotes: 1
Reputation: 143
If you attach an absolute styled div to a relative div I believe that it will stay stuck to wherever the relative div is.
<div id="veryHighDiv">
<div id="positionmMe"> </div>
</div>
#veryHighDiv {
position: relative;
}
#positionMe {
position: absolute;
top: 50px;
left: 100px;
}
Upvotes: 1
Reputation: 295
Since you ultimately want it to be fixed position, there's no need to start it off as relative since changing it to fixed dynamically will ruin any CSS work you do within relative (or usually absolute as well) positioning.
If it were me, I'd write a function to calculate where the fixed element should be, and then be sure to call that on all window events like load and resize so that it stays in place. Here's a sample, but you'll likely need to change it based on the rest of your CSS:
<script>
$(window).load(function() {
positionElem();
});
$(window).resize(function() {
positionElem();
});
function positionElem() {
var padFromDiv = 30; // amount of padding you want from your div
var newX = 0; // initialize newX at 0
// get difference in window and veryHighDiv if window is larger
if ($(window).width() > $('#veryHighDiv').width()) {
newX = ($(window).width()-$('#veryHighDiv').width());
}
newX+=padFromDiv;
$('#positionMe').css('left',newX);
}
</script>
Upvotes: 2