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

前端 未结 6 897
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:08

    I think you can use display: inline-block on the element you want to center and set text-align: center; on its parent. This definitely center the div on all screen sizes.

    Here you can see a fiddle: http://jsfiddle.net/PwC4T/2/ I add the code here for completeness.

    HTML

    Hi

    CSS

    #container
    {
        text-align: center;
    }
    #main
    {
        display: inline-block;
    }
    #somebackground
    {
        text-align: left;
        background-color: red;
    }
    

    For vertical centering, I "dropped" support for some older browsers in favour of display: table;, which absolutely reduce code, see this fiddle: http://jsfiddle.net/jFAjY/1/

    Here is the code (again) for completeness:

    HTML

    
        
    Hi

    CSS

    body, html
    {
        height: 100%;
    }
    #table-container
    {
        display:    table;
        text-align: center;
        width:      100%;
        height:     100%;
    }
    #container
    {
        display:        table-cell;
        vertical-align: middle;
    }
    #main
    {
        display: inline-block;
    }
    #somebackground
    {
        text-align:       left;
        background-color: red;
    }
    

    The advantage of this approach? You don't have to deal with any percantage, it also handles correctly the tag (html5), which has two different sizes (one during load, one after load, you can't fetch the tag size 'till video is loaded).

    The downside is that it drops support for some older browser (I think IE8 won't handle this correctly)

提交回复
热议问题