CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

前端 未结 6 901
Happy的楠姐
Happy的楠姐 2020-12-04 12:54

I\'ve seen a million questions about how to center a block element and there seem to be a couple popular ways to do it, but they all rely on fixed pixels widths. Then either

6条回答
  •  旧巷少年郎
    2020-12-04 13:18

    From Chris Coyier's article on centering percentage width elements:

    Instead of using negative margins, you use negative translate() transforms.

    .center {
      position: absolute;
      left: 50%;
      top: 50%;
    
      /*
      Nope =(
      margin-left: -25%;
      margin-top: -25%;
      */
    
      /* 
      Yep!
      */
      transform: translate(-50%, -50%);
    
      /*
      Not even necessary really. 
      e.g. Height could be left out!
      */
      width: 40%;
      height: 50%;
    }
    

    Codepen

提交回复
热议问题