I have a sticky div which stays on top if I scroll past it. But it resize to the full screen size and I want it to keep the same size.
Here is CSS-code for the wrapper and the sticky class:
.wrapper{
margin: 0 auto;
width: 100%;
height: 180px;
background-color:#fff;
border-top: 0;
-webkit-box-shadow: 0 8px 6px -6px #B8B8B8;
-moz-box-shadow: 0 8px 6px -6px #B8B8B8;
box-shadow: 0 8px 6px -6px #B8B8B8;
}
.sticky {
width: 100%;
position: fixed;
left: 0;
top: 0;
z-index: 100;
border-top: 0;
padding-left: 15px;
padding-right: 15px;
-webkit-box-shadow: 0 8px 6px -6px #B8B8B8;
-moz-box-shadow: 0 8px 6px -6px #B8B8B8;
box-shadow: 0 8px 6px -6px #B8B8B8;
}
And here is the JS code:
var global = {};
$(document).ready(function(){
var element = $(".wrapper");
offset = element.offset();
global.top = offset.top;
global.height = element.outerHeight();
});
$(window).scroll(function () {
var scroll_top = $(document).scrollTop();
if (scroll_top > global.top ) {
$('.wrapper').addClass('sticky');
$("body").css({
"padding-top": global.height
});
} else {
$('.wrapper').removeClass('sticky');
$("body").css({
"padding-top": 0
});
}
});
I created also a fiddle: http://jsfiddle.net/44ep8dz4/1/
You could use inherit
:
.sticky {
width: inherit;
...
}
For the small screen problem, add this:
@media(max-width: 768px) {
.sticky {
width: 100%;
}
}
This overrides the width: inherit
if the screen size is smaller than 768px.
Demo jsfiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.