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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12313989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:07:36  来源:igfitidea点击:

fit div width to content and not to parent

cssinheritancenowrap

提问by Redox

I want to make a label for a button that I have. My problem is that the label is wider then the button. I currently have it done like this (simple example):

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

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

The CSS:

CSS:

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

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

What I want is for the label to take the width of the label text itself without wrapping the text. At the moment it doesn't wrap the text, but I get an overflow of the text in the label box as that box only takes the maximum width of the container.

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

How can I force the label divto fit the size of the text and not inherit the width of the parent?

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

采纳答案by Akahadaka

I think you had exactly what you wanted. Perhaps check in another browser?
This is your code: jsfiddle

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

回答by Lucas Green

HTML:

HTML:

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

CSS:

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;
}

回答by miksiii

You can use white-space: nowrap;property in a parent class and width: 100%;in a child.

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

I hope you find this useful.

希望这个对你有帮助。