How to center an element vertically in css in a scrollable container

后端 未结 1 1749
醉话见心
醉话见心 2020-12-07 04:08

I am trying to center an element vertically inside a parent element using css. The parent element has a dynamic height and I would like the parent box to scroll if the heigh

1条回答
  •  忘掉有多难
    2020-12-07 04:29

    You can use flexbox with auto margins:

    Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

    It works because only positive free space is distributed.

    #wrapper {
      display: flex;
    }
    .center {
      margin: auto;
    }
    

    #wrapper {
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      overflow: auto;
      position: absolute;
      display: flex;
    }
    .center {
      width: 300px;
      height: 300px;
      background-color: yellow;
      margin: auto;
    }
    Hello

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