center aligning a fixed position div

前端 未结 13 588
走了就别回头了
走了就别回头了 2020-11-29 15:55

I\'m trying to get a div that has position:fixed center aligned on my page.

I\'ve always been able to do it with absolutely positioned divs using this \

相关标签:
13条回答
  • 2020-11-29 16:05

    I used the following with Twitter Bootstrap (v3)

    <footer id="colophon" style="position: fixed; bottom: 0px; width: 100%;">
        <div class="container">
            <p>Stuff - rows - cols etc</p>
        </div>
    </footer>
    

    I.e make a full width element that is fixed position, and just shove a container in it, the container is centered relative to the full width. Should behave ok responsively too.

    0 讨论(0)
  • 2020-11-29 16:07

    Koen's answer doesn't exactly centers the element.

    The proper way is to use CCS3 transform property. Although it's not supported in some old browsers. And we don't even need to set a fixed or relative width.

    .centered {
        position: fixed;
        left: 50%;
        transform: translate(-50%, 0);
    }
    

    Working jsfiddle comparison here.

    0 讨论(0)
  • 2020-11-29 16:09

    if you don't want to use the wrapper method. then you can do this:

    .fixed_center_div {
      position: fixed;
      width: 200px;
      height: 200px;
      left: 50%;
      top: 50%;
      margin-left: -100px; /* 50% of width */
      margin-top: -100px; /* 50% of height */
    }
    
    0 讨论(0)
  • 2020-11-29 16:12

    You could use flexbox for this as well.

    .wrapper {
      position: fixed;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      
      /* this is what centers your element in the fixed wrapper*/
      display: flex;
      flex-flow: column nowrap;
      justify-content: center; /* aligns on vertical for column */
      align-items: center; /* aligns on horizontal for column */
      
      /* just for styling to see the limits */
      border: 2px dashed red;
      box-sizing: border-box;
    }
    
    .element {
      width: 200px;
      height: 80px;
    
      /* Just for styling */
      background-color: lightyellow;
      border: 2px dashed purple;
    }
    <div class="wrapper"> <!-- Fixed element that spans the viewport -->
      <div class="element">Your element</div> <!-- your actual centered element -->
    </div>

    0 讨论(0)
  • 2020-11-29 16:12

    If you want to center aligning a fixed position div both vertically and horizontally use this

    position: fixed;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    
    0 讨论(0)
  • 2020-11-29 16:15
    <div class="container-div">
      <div class="center-div">
    
      </div>
    </div>
    
    .container-div {position:fixed; left: 0; bottom: 0; width: 100%; margin: 0;}
    .center-div {width: 200px; margin: 0 auto;}
    

    This should do the same.

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