You can set the width property of the children to fit-content . Doing so will make these elements take up only as much horizontal space as they need and is available within the parent. You can also set width to max-content but this will ignore the width of the parent and content will extend as far as any descendants need and possibly overflow the parent.
<div class="parent">
<div class="child">
Content for child
</div>
</div>
Support for fit-content is pretty good (caniuse?). There's support for fit-content on pretty much all the major desktop browsers (except IE), and unknown support on some of the mobile browsers.
If you truly want the parent div to collapse around its child elements (for whatever reason, based on what you're trying to accomplish) and you then want to center that div , then @Vector's answer is spot on, use display: table with margin: 0 auto . If it's ok for the div to remain expanded to the full width of the container in which you're trying to center your children, then you have at least a couple more options, again depending on your particular situation. You can use text-align: center .
You could also use the newer display: flex with justify-content: center , depending on the level of browser compatibility you're supporting, of course.
5条答案
按热度按时间dkqlctbz1#
你应该使用
display: table;
它将缩小到它的内容的大小,也可以居中和定位,而不必分配一个给定的宽度。演示http://jsfiddle.net/kevinPHPkevin/9VRzM/
wqnecbli2#
You can set the width property of the children to
fit-content
. Doing so will make these elements take up only as much horizontal space as they need and is available within the parent.You can also set width to
max-content
but this will ignore the width of the parent and content will extend as far as any descendants need and possibly overflow the parent.Example:
Problem setup:
Solution:
Support for
fit-content
is pretty good (caniuse?). There's support forfit-content
on pretty much all the major desktop browsers (except IE), and unknown support on some of the mobile browsers.9q78igpj3#
If you truly want the parent
div
to collapse around its child elements (for whatever reason, based on what you're trying to accomplish) and you then want to center thatdiv
, then @Vector's answer is spot on, usedisplay: table
withmargin: 0 auto
.If it's ok for the
div
to remain expanded to the full width of the container in which you're trying to center your children, then you have at least a couple more options, again depending on your particular situation.You can use
text-align: center
.You could also use the newer
display: flex
withjustify-content: center
, depending on the level of browser compatibility you're supporting, of course.hgqdbh6s4#
您是否尝试过使用
display: inline-block
?DIV将占用100%的宽度,因为它们是块元素。zaq34kh65#
如果您修改DOM,在div内添加额外的html元素,并导致其展开,一个简单的解决方案是将该css添加到这些额外html元素的根元素中:
最大宽度:适合内容;
这将防止它们扩展父div的宽度。