JSFiddle - React, Tailwind, and code Playground
by gion_13
HTML
<div class="container center">
<div class="frame top">
<p class="center">TOP</p>
</div>
<div class="frame right">
<p class="center">RIGHT</p>
</div>
<div class="frame bottom">
<p class="center">BOTTOM</p>
</div>
<div class="frame left">
<p class="center">LEFT</p>
</div>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</div>
CSS
.container{
border : 4px dotted blue;
height : 400px;
width : 400px;
overflow-x : hidden;
overflow-y : auto;
}
.center{
position : absolute;
top : 50%;
left : 50%;
-webkit-transform : translate(-50%,-50%);
-moz-transform : translate(-50%,-50%);
-o-transform : translate(-50%,-50%);
-ms-transform : translate(-50%,-50%);
transform : translate(-50%,-50%);
}
.frame{
width : 200px;
height : 200px;
border : 1px solid red;
position : relative;
margin : 0 auto;
}
JavaScript
$('.container')
.scroll(function(e){
var s = $(this).scrollTop();
var frames = $(this).find('.frame');
frames.filter('.bottom').each(function(){$(this).css('margin-top',+$(this).css('top') - s);});
frames.filter('.right').each(function(){$(this).css('margin-left',+$(this).css('left') - s);});
frames.filter('.left').each(function(){$(this).css('margin-left',+$(this).css('left') + s);});
})
.find('.frame')
.each(function(){
var $this = $(this),
i = $this.index(),
container = $this.parents('.container:first'),
container_offset = container.offset(),
offset = $this.offset(),
w = $this.width(),
h = $this.height(),
o = {
top : (offset.top - container_offset.top) / 2,
left : (offset.left - container_offset.left) / 2
},
padding = {
top : (container.width() - w) / 2,
left : (container.height() - h) / 2
},
css = {},
is = {
right : $this.hasClass('right'),
left : $this.hasClass('left'),
top : $this.hasClass('top'),
bottom : $this.hasClass('bottom')
};
$.each(is,function(k,v){
if(v)
{
var margin = ['right','left'].indexOf(k) == -1 ? 'left' : 'top';
var sign = ['right','bottom'].indexOf(k) == -1 ? 1 : -1;
css['margin-' + margin] = sign * o[margin];
}
});
/*
if(!('bottom' in css))
css['margin-top'] = ($this.offset().top - $this.parents('.container:first').offset().top) / 2;
if(!('left' in css) && !('right' in css))
{
var sign = ('bottom' in css) ? 1 : -1;
css['margin-left'] = sign * w / 2;
}
*/
...