Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
41
rated 0 times [  48] [ 7]  / answers: 1 / hits: 7163  / 10 Years ago, wed, december 10, 2014, 12:00:00

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/


More From » jquery

 Answers
4

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.


[#40712] Tuesday, December 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;