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

前端 未结 6 906
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:15

    Centering both horizontally and vertically

    Actually, having the height and width in percents makes centering it even easier. You just offset the left and top by half of the area not occupied by the div.

    So if you height is 40%, 100% - 40% = 60%. So you want 30% above and below. Then top: 30% does the trick.

    See the example here: http://dabblet.com/gist/5957545

    Centering only horizontally

    Use inline-block. The other answer here will not work for IE 8 and below, however. You must use a CSS hack or conditional styles for that. Here is the hack version:

    See the example here: http://dabblet.com/gist/5957591

    .inlineblock { 
        display: inline-block;
        zoom: 1;
        display*: inline; /* ie hack */
    }
    

    EDIT

    By using media queries you can combine two techniques to achive the effect you want. The only complication is height. You use a nested div to switch between % width and

    http://dabblet.com/gist/5957676

    @media (max-width: 1000px) {
        .center{}
        .center-inner{left:25%;top:25%;position:absolute;width:50%;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
    }
    @media (min-width: 1000px) {
        .center{left:50%;top:25%;position:absolute;}
        .center-inner{width:500px;height:100%;margin-left:-250px;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
    }
    

提交回复
热议问题