如何让物体不占用其自然宽度

时间:2014-07-30 12:34:40

标签: html css layout

我有一个垂直对齐的DOM对象。其中一个,比如<div id="foo">,其自然宽度比其他宽度宽。我希望该元素不占用其自然宽度,但让其他部分(其兄弟姐妹中最宽的部分,或父宽度,无论哪个更宽)确定宽度,并让<div id="foo">的水平溢出部分隐藏。

<div>
  <div>some content</div>
  <div id="foo">a content with very wide width</div>
  ...
  <div>some content</div>
</div>

我希望它看起来像这样:

enter image description here

其中包含内容"Another content"的div确定宽度,因为其自然宽度比除<div id="foo">之外的其他兄弟更宽。

我怎么能用CSS做到这一点?

3 个答案:

答案 0 :(得分:1)

您可以使用显示表属性和负边距来将元素的虚拟宽度减少为空。的 DEMO HTML测试

<div class="content">
  <div> blab bla bla bla bla </div>
  <div class="refW">my width</div>
  <div>blop blop blop blop blop blop blop blop blop</div>
</div>

CSS测试

.content {
  display:table;
  width:0%;/* will expand to fit to content */
  margin: auto;
  overflow:hidden;
  border:solid;
}
.content div {
  white-space:nowrap ;  
  margin-right:-9999px;
  background:red;

}
.content div.refW {
  margin-right:0px;
  background:green;
}

答案 1 :(得分:0)

如果您希望子div的内容占用其父div的宽度,则需要将overflow:hidden属性添加到父div。通过这种方式,即使子项的宽度大于父项,子项也将使用其父项。

demo fiddle

代码段:

CSS类

#foo {
    width:500px;
}
.parent {
    width:400px;
    height:auto;
    overflow:hidden;
}

<强> HTML

<div class="parent">
    <div>some content some contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome contentsome content</div>
    <div id="foo">a content with very wide width a content with very wide widtha content with very wide widtha content with very wide widtha content with very wide widtha content with very wide widtha content with very wide widtha content with very wide widtha content with very wide widtha content with very wide width</div>
    <div>some content</div>
</div>

答案 2 :(得分:0)

我不确定你要求提出,但是:

尝试为所有元素的包装器设置宽度

<div style="width: xxxx; overflow:hidden;">
  ...
  ...
  ...
  ...
</div>

然后将100%宽度设置为包装器内的较宽对象(这样,您可以将其宽度调整到包装器的宽度)

<div>
  <div>some content</div>
  <div id="foo">a content with very wide width</div>
  ...
  <div>some content</div>
</div>



<style>
  #foo {
     max-width:100%;
  }
</style>