html css:防止div宽度扩展到可用宽度

bvjxkvbb  于 2022-12-09  发布在  其他
关注(0)|答案(5)|浏览(206)

如何防止div扩展?我希望div中的元素不占用100%的可用空间,并且具有它的子元素所具有的宽度。我需要这样来水平居中父div。诀窍是子元素应该共享float:left或display:inline-block和fluid width,因此可以有更少的子元素行。
我不能将每一行 Package 在它自己的div中,因为这会破坏响应式设计。

dkqlctbz

dkqlctbz1#

你应该使用display: table;它将缩小到它的内容的大小,也可以居中和定位,而不必分配一个给定的宽度。
演示http://jsfiddle.net/kevinPHPkevin/9VRzM/

wqnecbli

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:

.parent {
  width: 15rem;
  height: 5rem;
  border: 1px solid blue;
}

.child {
  border: 1px solid red;
}
<div class="parent">
  <div class="child">
    Content for child
  </div>
</div>

Solution:

.parent {
  width: 15rem;
  height: 5rem;
  border: 1px solid blue;
}

.child {
  width: fit-content;
  border: 1px solid red;
}
<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.

9q78igpj

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 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 .

.content {
  text-align: center;
  border-style: solid;
  border-width: thin;
}

.content span {
  display: inline;
  border-style: solid;
  border-width: thin;
}
<div class="content">
  <div>Test</div>
  <div>Test</div>
</div>

You could also use the newer display: flex with justify-content: center , depending on the level of browser compatibility you're supporting, of course.

.content {
  display: flex;
  justify-content: center;
  border-style: solid;
  border-width: thin;
}

.content div {
  border-style: solid;
  border-width: thin;
}
<div class="content">
  <div>Test</div>
  <div>Test</div>
</div>
hgqdbh6s

hgqdbh6s4#

您是否尝试过使用display: inline-block?DIV将占用100%的宽度,因为它们是块元素。

zaq34kh6

zaq34kh65#

如果您修改DOM,在div内添加额外的html元素,并导致其展开,一个简单的解决方案是将该css添加到这些额外html元素的根元素中:
最大宽度:适合内容;
这将防止它们扩展父div的宽度。

相关问题