问题描述
如何设置DIV的宽度,就像设置 float:left
但不设置浮点数时的宽度一样? width:auto
似乎没有做到(在Chrome中)。
How can I have a DIV's width behave like it does when float:left
is set, but without setting a float? width:auto
doesn't seem to do it (in chrome).
我正在尝试获得类似以下内容可以工作...
I am trying to get something like the following to work...
.center
{
margin-left: auto;
margin-right: auto;
width: auto;
}
推荐答案
使用内联块的解决方案
您可以尝试 display:inline-block
并查看是否适合您的情况。但是,您将无法使用 margin-left:auto
& margin-right:auto
,因为该技术需要宽度值。
Solution with inline-block
You could try display: inline-block
and see if that works in your situation. However, you won't be able to center it using margin-left: auto
& margin-right: auto
because that technique requires a width value.
如果可能,请使用显示:内联块
,并在其容器上设置 text-align:center
。
If possible, use display: inline-block
and set text-align: center
on it's container.
<div style="text-align: center">
<div style="display: inline-block;">
This will expand only as far as it needs to
</div>
</div>
使用Flexbox +容器div的解决方案
上面的原始答案是在Flexbox实施之前于2011年编写的。您可以达到类似的效果
Solution using Flexbox + container div
The original answer above was written in 2011, before flexbox was implemented. You can achieve a similar effect
<div style="display: flex; justify-content: center;">
<div>
This will expand only as far as it needs to
</div>
</div>
无容器div的解决方案
有没有父元素的另一种方法。
Solution without container div
There is another way to do this without a parent element.
- 将显示设置为
inline-block
以使div宽度适合其内容 - 使用
位置:相对
和左:50%
定位其位置左边缘到其包含元素的50%。 - 使用
transform:translateX(-50%)
会移动元素
- Set display to
inline-block
to make the div width fit to its content. - Use
position: relative
andleft: 50%
to position its left edge to 50% of its containing element. - Use
transform: translateX(-50%)
which will "shift" the element to the left by half its own width.
.center {
display: inline-block;
position: relative;
left: 50%;
transform: translateX(-50%);
}
这篇关于如何让div自动设置自己的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!