CSS 调整 <div> 的大小以适合文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16133966/
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 22:33:25  来源:igfitidea点击:

CSS resizing the <div> to fit the text

css

提问by HymanRoster

I have a <div>called "container" which wrap another <div>called "box". "box" has text inside it.

我有一个<div>叫做“容器”的东西,它包裹着另一个<div>叫做“盒子”的东西。“盒子”里面有文字。

The problem is I can't seem to resize the <div class="box">to fit the text. I also got a diagram to explain my situation.

问题是我似乎无法调整大小<div class="box">以适合文本。我还得到了一张图表来解释我的情况。

figure

数字

<!DOCTYPE html>
<meta charset="utf-8" />
<link rel="stylesheet" href="float.css">
<div class="container">
    <br>
    <br>
    <br>
    <br>
    <div class="box">Hello my name is Hyman</div>
</div>
<div class="container">
    <br>
    <br>
    <br>
    <br>
    <div class="box">Hello my name is Hyman</div>
</div>

My CSS

我的 CSS

.container {
    background-color: #ED8713;
    height: 300px;
    width: 300px;
    margin: 60px;
    margin-top: 50px;
}
.box {
    background-color: #FFFFFF;
    width: 270px;
    margin: 0 auto;
    margin-top: 15px;
    text-align: center
}

采纳答案by Niet the Dark Absol

You know what? We're all idiots. Here's the REAL answer:

你知道吗?我们都是白痴。这是真正的答案:

HTML:

HTML:

<div class="container">
    <br>
    <br>
    <br>
    <br>
    <span class="box">Hello my name is Hyman</span>
</div>

CSS:

CSS:

.container {
    background-color: #ED8713;
    height: 300px;
    width: 300px;
    margin: 60px;
    margin-top: 50px;
    text-align: center;
}
.box {
    background-color: #FFFFFF;
    margin-top: 15px;
}

回答by Alba Mendez

Let the .boxbe an inline-block...

.box是一个inline-block...

.box {
  display: inline-block;
}

...and center it!

...并居中!

.container {
  text-align: center;
}

Adding this two snippets to your stylesheet and removing the width: 270pxshould suffice.

将这两个片段添加到您的样式表并删除width: 270px应该就足够了。

回答by Melki

You should remove the width or set it to auto : width : auto

您应该删除宽度或将其设置为 auto : width : auto

回答by Sikander

You can do a trick make the inner div color invisible with sane background color as parent div , now put the text in

您可以做一个技巧,使内部 div 颜色不可见,而背景颜色为父 div ,现在将文本放入

<span style="background-color:#ffffff;" >Text </span>

回答by Niet the Dark Absol

Remove the widthon the .box, and add display:inline-blockinstead.

删除width上的.box,然后添加display:inline-block

回答by Casey Dwayne

This will stretch the container div to the width of the parent.

这会将容器 div 拉伸到父级的宽度。

.box {
    width:100%;
}