20

如何防止 div 扩展?我希望带有元素的 div 不占用 100% 的可用空间并且具有它的孩子所具有的宽度。我需要这个来水平居中父 div。诀窍是子元素应该共享 float:left 或 diplay: inline-block 和流体宽度,因此可以有几行子元素。

我不能将每一行包装在自己的 div 中,因为它会破坏响应式设计。

4

4 回答 4

15

您应该使用display: table;它将缩小到其内容的大小,并且还可以居中和定位,而无需分配给定的宽度。

演示http://jsfiddle.net/kevinPHPkevin/9VRzM/

于 2013-08-08T19:49:41.623 回答
9

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.

于 2019-08-28T20:05:36.350 回答
2

如果您真的希望父div级围绕其子元素折叠(无论出于何种原因,基于您要完成的任务),然后您想要将其居中div,那么@Vector 的答案就是正确的,使用display: tablewith margin: 0 auto

如果可以div保持扩展至您试图让孩子居中的容器的整个宽度,那么您至少还有几个选择,这取决于您的具体情况。

您可以使用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>

当然,您也可以使用较新display: flex的 with justify-content: center,具体取决于您支持的浏览器兼容性级别。

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

于 2017-06-24T17:16:04.133 回答
0

你试过用display: inline-block吗?DIV 将占据 100% 的宽度,因为它们是块元素。

于 2013-08-08T19:43:56.177 回答