如何在CSS中居中未知宽度的框? [英] How can I center a box of unknown width in CSS?

查看:120
本文介绍了如何在CSS中居中未知宽度的框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个html:

<div class="object-box">
    <img ... />
    <span class="caption">This is the caption</span>
</div>

这个CSS附带:

.object-box .caption, .object-box img {
    display: block;
}
.object-box {
    border: 1px solid;
}



我希望周围的div收缩包装到其内容。我可以通过使用 float:... display:inline-block 来实现。但是,我也希望它在页面上居中,使用 margin:auto 。这两种方法似乎不兼容。

I would like the surrounding div to shrink-wrap to its contents. I can achieve this by using float: ... or display: inline-block. However, I'd also like it to be centered on the page, using margin: auto. The two approaches don't seem to be compatible.

是否可以创建这样的收缩包装,居中的容器,而不添加包装元素?

Is it possible to create such a shrink-wrapped, centered container, without adding a wrapper element?

jsFiddle 此处

jsFiddle here

推荐答案

<!doctype html>
<html>
    <head>
    <title>ugh</title>
    <style>
        div#not-floated {
        display:table;
        margin:0 auto;
        }

        div#floated {
        float:right;
        position:relative;
        right:50%;
        }

        div#floated-inner {
        float:left;
        position:relative;
        left:50%;
        }

    </style>
    <!--[if lt IE 8]>
        <style type="text/css">

            #container { text-align: center; }
                #container * { text-align: left; }
                div#not-floated {
                    zoom: 1;
                    display: inline;
                }
        </style>
    <![endif]-->

    </head>

    <body>


    <div id="container">
        <div id="not-floated">
        <img src="http://www.google.co.uk/logos/d4g_worldcup10_uk-hp.jpg"><br>
        ok.
        </div>
    </div>
    <div id="floated-container">
        <div id="floated"><div id="floated-inner">
        <img src="http://www.google.co.uk/logos/d4g_worldcup10_uk-hp.jpg">
        </div></div>
    </div>

    </body>

</html>

简单的解释是... display:table; 使它在现代浏览器中收缩包装,这是在现代浏览器中使用margin:0 auto;

Simple explanation is.. display:table; causes it to shrinkwrap in modern browsers, thats the only way to center widthless block level in modern browsers with margin:0 auto;.

在IE中,使用父元素来设置text-align:center在缩减的 display:inline 块级元素。

In IE it's a matter of using parent element to set text-align:center on your shrinkwrapped display:inline block level element.

使用IE的容器浮动其50%的数学。

For floats its just 50% math using containers for IE.

这篇关于如何在CSS中居中未知宽度的框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆