Set a Fixed div to 100% width of the parent container

前端 未结 7 1669
忘了有多久
忘了有多久 2020-12-09 00:52

I have a wrapper with some padding, I then have a floating relative div with a percentage width (40%).

Inside the floating relative div I have a fixed div which I w

7条回答
  •  孤城傲影
    2020-12-09 00:56

    On top of your lastest jsfiddle, you just missed one thing:

    #sidebar_wrap {
      width:40%;
      height:200px;
      background:green;
      float:right;
    }
    #sidebar {
      width:inherit;
      margin-top:10px;
      background-color:limegreen;
      position:fixed;
      max-width: 240px; /*This is you missed*/
    }
    

    But, how this will solve your problem? Simple, lets explain why is bigger than expect first.

    Fixed element #sidebar will use window width size as base to get its own size, like every other fixed element, once in this element is defined width:inherit and #sidebar_wrap has 40% as value in width, then will calculate window.width * 40%, then when if your window width is bigger than your .container width, #sidebar will be bigger than #sidebar_wrap.

    This is way, you must set a max-width in your #sidebar_wrap, to prevent to be bigger than #sidebar_wrap.

    Check this jsfiddle that shows a working code and explain better how this works.

提交回复
热议问题