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

前端 未结 7 1668
忘了有多久
忘了有多久 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 01:15

    man your container is 40% of the width of the parent element

    but when you use position:fixed, the width is based on viewport(document) width...

    thinking about, i realized your parent element have 10% padding(left and right), it means your element have 80% of the total page width. so your fixed element must have 40% based on 80% of total width

    so you just need to change your #fixed class to

    #fixed{ 
        position:fixed;
        width: calc(80% * 0.4);
        height:10px;
        background-color:#333;
    }
    

    if you use sass, postcss or another css compiler, you can use variables to avoid breaking the layout when you change the padding value of parent element.

    here is the updated fiddle http://jsfiddle.net/C93mk/2343/

    i hope it helps, regards

提交回复
热议问题