让 CSS 元素自动调整大小到内容宽度,同时居中
我有一个 CSS 元素,周围有边框,其中可能有一个或多个框,因此整个 div 的宽度会根据其内部存在多少个框而变化。但是,我希望整个 div 位于屏幕中央。
通常,为了使内容居中,我只使用:
margin-left: auto;
margin-right: auto;
但是,这一次,我必须浮动元素或使其成为内联块,这样 div 的大小将根据内容调整大小,如果我这样做,边距- left 和 margin-right auto 不起作用,它总是停留在屏幕的左侧。
目前我有:
#boxContainer {
display:inline-block;
clear:both;
border:thick dotted #060;
margin: 0px auto 10px auto;
}
我还尝试使用 float: left
而不是 display: inline-block
。
有谁知道一种既可以将 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;
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.
Currently I have:
#boxContainer {
display:inline-block;
clear:both;
border:thick dotted #060;
margin: 0px auto 10px auto;
}
I also tried with float: left
instead of display: inline-block
.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否尝试过将其保留为内联块,并将其放入设置为
text-align: center
的块级元素内?例如
HTML
CSS
似乎按照您的描述工作: http://jsfiddle.net/pauldwaite/pYaKB/
Have you tried keeping it inline-block, and putting it inside a block-level element that’s set to
text-align: center
?E.g.
HTML
CSS
Seems to work as you describe: http://jsfiddle.net/pauldwaite/pYaKB/
不幸的是,我认为这不能仅通过 CSS 来实现。一旦知道其宽度(即在附加框之后),您始终可以使用 JavaScript 将
div
居中,例如:Unfortunately, this cannot be achieved through CSS solely I don't think. You could always use JavaScript to center the
div
once you know its width (i.e. after the boxes have been appended) for example: