Easy way to center variable width divs in CSS

前端 未结 4 760
清歌不尽
清歌不尽 2020-12-25 12:46

I\'m trying to center a Div that will have varying width\'s (based on content of a website).

I read about a relative positioning technique here:

http://www.t

4条回答
  •  渐次进展
    2020-12-25 13:19

    Now with flex-box you can easily achieve this with justify-content: center;.

    #container{
      background: gray;
      display: flex;
      justify-content: center;
    }
    This is a centered div This is a centered div This is a centered div This is a centered div

    This can also be achieved by applying margin: auto to the containers child selector #container>*.

    #container{
      background: #c7c7c7;
    }
    #container>*{
      margin: auto;
    }
    This is a centered div This is a centered div This is a centered div This is a centered div

    Note: content div is styled inline as these styles are generated styles and are out of the scope of this question.

提交回复
热议问题