简体   繁体   中英

Width of element with fixed position Bootstrap

I got an element with width=auto . When when I add position: fixed to that element, it visually changes its width. How can I keep the aspect of the element after adding position: fixed ? I want a responsive and centered element with position 'fixed'.

This is an example of the problem (class first and first_top ) : http://jsfiddle.net/nWHSH/

Your problem was in your first_top CSS.

http://jsfiddle.net/gespinha/nWHSH/6/

This should solve your problem, just change your CSS to:

.first_top {
    position: fixed;
    top: 0;
    background: #FFF;
    z-index: 2;
    left: 0;
    right: 0;
    max-width: 720px;
    margin: 0 auto;
} 

The problem was about the fixed positioning. Fixed and absolute positioned elements are detached from the actual document flow , so they tend to not react with other elements naturally, they interact with the document it self.

So in order to force the order within the flow, you have to guide that sam element and make him follow a flow that is not the main one, but is similar, giving the user the idea that it is really being manipulated by the interaction with the other objects in the DOM.

demo

centring element after position fixed

var elem = $('.first');
    var firstTop = elem.offset().top, firstH = elem.height();
    $(window).scroll(function(){
      if( $(window).scrollTop() > firstTop ) {
        elem.removeClass('first_top').addClass('first_top');
        $('.sticker').css({display: 'block', height: firstH});
          $(".first_top").css("left", ($(window).width()- $(".first_top").width())/2);
      } else {
        $('.first').removeClass('first_top');
        $('.sticker').css({display: 'none', height: '0'});
      }
    });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM