CSS Fixed position with Auto Margin

后端 未结 3 1035
感动是毒
感动是毒 2020-12-05 14:00

I want a component that keeps horizontal center of the page (two-columns), and I have a sub-component (right column) that I want its position to be fixed, so the sub-compone

相关标签:
3条回答
  • 2020-12-05 14:54

    I like to use a wrapper as asolution for this problem:

    .wrapper {
      position: fixed;
      width: 100%;
      top: 0px;
    }
    .wrapper .right {
      width: 500px;
      margin: auto;
    }
    
    0 讨论(0)
  • 2020-12-05 14:59

    You can use margin: 0 auto with position: fixed if you set left and right.

    .wrapper {
        position:fixed;
        top: 0;
        left: 0;
        right: 0;
        width: 500px;
        margin: 0 auto;
    }
    

    This also works with position: absolute; and vertically.

    Demo: http://codepen.io/pstenstrm/pen/myaWVJ

    0 讨论(0)
  • 2020-12-05 15:00

    You cant do that with margin:auto, but you can do something like this:

    #CSS-SELECTOR-YOU-ARE-USING{
        background:#FF0000; // Just so you can see whats going on
        position:fixed; // Position the element
        right:50%; // Move it to the right for 50% of parent element
        margin-right:-250px; // You need here to put 1/2 of what you have below in width
        width:500px;
    }
    

    This way you move element to the right for 50%, and then move it back for half of its width. That way you get centered element with position:fixed.

    0 讨论(0)
提交回复
热议问题