【问题标题】:how to collapse width of parent element to total width of child elements如何将父元素的宽度折叠到子元素的总宽度
【发布时间】:2013-08-29 05:21:55
【问题描述】:

我的父元素宽度占据了父元素的整个 100% 宽度。

相反,我希望父宽度折叠到子元素的总宽度。

jsfiddle:http://jsfiddle.net/z9Unk/232/

注意红色边框的父元素宽度大于绿色子元素的总宽度。我想折叠父宽度。

请告知必要的更改。

HTML

<div class="item1">
  <div class="item2">
      item2
  </div>
  <div class="item2">
      item2
  </div>
</div>

CSS:

.item1 {
  position:relative;
  white-space: nowrap;
  width:auto;
  overflow: hidden;
  border:2px solid red;
}

.item2 {
 position:relative;
  display:inline-block;
  background-color: green;
  width : 255px;
  height : 205px;
  margin-right:6px;
  border:1px solid blue;
}

【问题讨论】:

  • 谢谢大家...我已经解决了
  • 将最适合您的方法标记为问题的答案。谢谢:)

标签: html css


【解决方案1】:

.item1 是块级元素,默认占其父级宽度的 100%。

您可以将.item1 元素的显示 类型更改为tableinline-block

.item1 {
    /*  other CSS declarations */
    /* display: inline-block; */ /* Or */
    display: table;
}

这里是Fiddle


注意:如果 Internet Explorer 没有在兼容性视图中运行,则没问题

但是要强制 IE 在标准模式下运行,您可以在 &lt;head&gt; 部分添加以下 &lt;meta&gt; 标签:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

更多信息:http://msdn.microsoft.com/en-us/library/cc288325%28VS.85%29.aspx

【讨论】:

  • 希望您在使用 Internet Explorer 时没有问题
【解决方案2】:

Item1 将始终扩展到其父级的宽度,因为它被设置为 display:block。

解决此问题的一种方法是添加到 Item1:

浮动:左

【讨论】:

    【解决方案3】:

    另一种方法是为 CSS 属性 width 使用 fit-content 值。但是只有 Firefox 和 Chrome 支持它……

    示例:

    .item1 {
      position:relative
      white-space: nowrap;
      width: -moz-fit-content;
      width: -webkit-fit-content;
      width: fit-content;
      overflow: hidden;
      border:2px solid red;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 2013-09-22
      • 2015-06-08
      • 2015-04-17
      • 2012-09-18
      • 1970-01-01
      • 2014-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多