将div宽度适合内容而不是父级

时间:2012-09-07 07:54:38

标签: css inheritance nowrap

我想为我拥有的按钮制作标签。我的问题是标签比按钮宽。我现在这样做(简单的例子):

<div class="parent_container_the_icon">
    <div class="label">
        This is the label text
    </div>
<div>

CSS:

.parent_container_the_icon {
    height: 50px;
    width: 50px;
    float: left;
}

.label {
    display: block;
    position: absolute;
    white-space: nowrap;
}

我想要的是标签在不包装文本的情况下获取标签文本本身的宽度。目前它没有包装文本,但是我在标签框中溢出了文本,因为该框只占用了容器的最大宽度。

如何强制标签div符合文本大小而不继承父级的宽度?

3 个答案:

答案 0 :(得分:2)

HTML:

 <div class="parent_container_the_icon">
      <div class="label">
           This it the label text
      </div>
 <div>​

CSS:

.parent_container_the_icon {
    height: 50px;
    min-width: 50px; /*<== changed width to min-width*/
    float: left;
}

.label {
    /*removed position:absolute*/
    display: block;
    white-space:nowrap;
}

答案 1 :(得分:2)

我认为你有你想要的。也许检查另一个浏览器?
这是您的代码:jsfiddle

答案 2 :(得分:0)

您可以在父类中使用white-space: nowrap;属性,在子级中使用width: 100%;

我希望你觉得这很有用。

相关问题