scroll with position:Fixed losing the right margin

Asked

Viewed 225 times

1

When I scroll down, the div#chat, is fixed everything straight. However the problem is that the layout breaks losing the right margin. How can I solve this problem?

$(document).ready(function() {

   var nav = $('#chat');

   $(window).scroll(function() {
     if ($(this).scrollTop() > 300) {

       nav.addClass("f-nav");
     } else {
       nav.removeClass("f-nav");
     }
   });

   
 });
    .f-nav {
        z-index: 9999;
        position: fixed;
        top: 0;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div style="width:100%; display:flex;">

  <div style="width:70%; height: 2000px; background-color: #ff9d58; margin:10px;">
  </div>


  <div id="chat" style="width:30%; height: 400px; background-color:#22792d; margin:10px;">
  </div>

</div>

  • 1

    Failed to add CSS for f-Nav, there is no position: Fixed in the code you posted.

  • Hello @Guilhermenascimento ! really was missing. Now I’ve updated the code thanks for warning.

1 answer

1

I suggest you do it with float and percentages. The problem you’re having is because when the element goes to fixed he leaves the block and occupies his real space.

Real space?

Yeah, you’re doing it 70% to a div and 30% the other, but also margin: 10px to both. Now that’s more than 100%, therefore when the div#chat passes to fixed the other takes the real space of 70% + 10px. Lowering the width percentage already solved the problem: http://jsfiddle.net/LcfLy7za/1/

Surgiro also put the whole CSS aside, and not inline in HTML because it’s easier to keep the code.

Doing everything with percentages:

body > div >div:first-child {
    float: left;
    width:68%;
    height: 2000px;
    background-color: #ff9d58;
    margin-left:1.5%;
}
#chat {
    float: left;
    width:28%;
    height: 400px;
    background-color:#22792d;
    margin-left:1.5%;
}

jsFiddle: http://jsfiddle.net/LcfLy7za/

  • thanks for the help, but the problem continues. As you suggested, if you reduce or increase the size of the browser, the layout still gives a dance. I may have to change the whole structure, but I still don’t know how.

  • @alexanderPataki I answered with code but then forgot to put the right code in jsFiddle... The percentage version looks like this: http://jsfiddle.net/LcfLy7za/2/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.