Dock title above container div

I have a problem with fixing the title above. The title is inside the div container, and I want it to stay on top even if the div container scrolls.

HTML:

<div class="wrapper">
    <div class="container">
        <div class="fixed">
            SHOULD BE FIXED
        </div>
    </div>
</div>

CSS:

.wrapper{
    width:300px;
    height:200px;
    margin:auto;
    border:1px solid #ddd;
    overflow-y:scroll;
    overflow-x:hidden;
}
.container{
    width:300px;
    position:relative;
    height:1000px;
    background:#111;
}
.fixed{
    background:#aaa;
    position:absolute;
    height:50px;
    width:100%;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

Here is the fiddle .

+4
source share
3 answers

Style position: fixedis a way:

.fixed {
    position: fixed;
    width: inherit;
}

DEMO: http://jsfiddle.net/F2Fhd/3/

+2
source

Changing the position .fixed class: absolute value for the position: fixed and set value of the width up to 300 pixels! :)

CSS

.fixed{
    background:#aaa;
    position:fixed;
    height:50px;
    width:300px;
    text-align:center;
    font-weight:bold;
    padding:15px 0;
    box-sizing:border-box;
    -moz-box-sizing: border-box;
}

http://jsfiddle.net/F2Fhd/4/

0
source

jquery crossbrowser.

<script>
$(document).ready(function() {
var div = $('**.fixed**');
var start = $(div).offset().top;
$.event.add(window, "scroll", function() {
    var ul = $(window).scrollTop();
    $(div).css('position',((ul)>start) ? 'fixed' : '');
});
});
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
    || location.hostname == this.hostname) {

    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
       if (target.length) {
         $('html,body').animate({
             scrollTop: target.offset().top
        }, 2000);
        return false;
    }
}
});
</script>
-1

Source: https://habr.com/ru/post/1535780/


All Articles