获取CSS元素以自动调整大小到内容宽度,并同时居中 [英] Getting a CSS element to automatically resize to content width, and at the same time be centered

查看:259
本文介绍了获取CSS元素以自动调整大小到内容宽度,并同时居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSS元素,它周围有一个边框,其中可能有一个或多个框,因此整个div的宽度会根据其中包含多少个框而变化。但是,我希望整个div集中在屏幕上。

I have a CSS element, with a border around it, that could have one or multiple boxes in it, so the width of the entire div changes depending on how many boxes are present inside of it. However, I want this whole div to be centered on the screen.

通常,要使内容居中,我只使用:

Usually, to center things, I just use:

margin-left: auto;
margin-right: auto;

但是,这一次,我必须浮动元素或使其内联块,因此大小div的大小将调整为该内容的大小,如果我这样做,则margin-left和margin-right自动将不起作用,它将始终停留在屏幕的左侧。

But, this time, I have to either float the element or make it inline-block so the size of the div will be resized to the content, and if I do that, the margin-left and margin-right auto does not work, it always just stays on the left side of the screen.

当前我有:

#boxContainer {
    display:inline-block;
    clear:both;
    border:thick dotted #060;
    margin: 0px auto 10px auto;
}

我也尝试过 float:left 而不是 display:inline-block

有人知道这两种方法都可以居中吗一个div并允许同时调整其大小以适应内容?任何帮助将不胜感激。

Does anyone know of a good way to both center a div and allow it to be resized to content simultaneously? Any help would be greatly appreciated.

推荐答案

您是否尝试过将其保持为内联块,并将其放入块级元素中设置为 text-align:center

Have you tried keeping it inline-block, and putting it inside a block-level element that’s set to text-align: center?

例如

<div id="boxContainerContainer">
    <div id="boxContainer">
        <div id="box1"></div>
        <div id="box2"></div>
        <div id="box3"></div>
    </div>
</div>



CSS



CSS

#boxContainerContainer {
    background: #fdd;
    text-align: center;
}

#boxContainer {
    display:inline-block;
    border:thick dotted #060;
    margin: 0px auto 10px auto;
    text-align: left;
}

#box1,
#box2,
#box3 {
    width: 50px;
    height: 50px;
    background: #999;
    display: inline-block;
}

似乎可以按照您描述的方式工作: http://jsfiddle.net/pauldwaite/pYaKB/

Seems to work as you describe: http://jsfiddle.net/pauldwaite/pYaKB/

这篇关于获取CSS元素以自动调整大小到内容宽度,并同时居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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