这个问题在这里已经有了答案:
How can I make a div not larger than its contents?
(43 个回答)
Width equal to content [duplicate]
(14 个回答)
2年前关闭。
我的想法是使div
中的每个元素具有 .main_content
的 s类,使其宽度等于其中文本的宽度。我该怎么做?
如您所见,每一个的宽度( span
、 h2,
p
和 h6
)与 .main_content
相同。 div
.红色边框证明了这一点。
那么,如何使每个 div 的宽度适合这些 div 中的文本呢? (只有 CSS)
.main_content {
width: 100%;
height: 400px;
font-weight: 800;
}
.main_content > * {
border: 1px solid red;
display: block;
margin-bottom: 30px;
text-align: center;
}
<div class="first_article">
<div class="first_content">
<div class="main_content">
<span class="growth">Growth</span>
<h2>5 compelling user referral campaign examples</h2>
<p>Jumpstarts your user referral engine with these 5 approaches toreferral campaigns from popular apps.
</p>
<h6>Author</h6>
</div>
</div>
</div>
P: 我一直在尝试手动设置
width
的大小每个元素的。但是代码太多了。有什么聪明的方法吗?
最佳答案
你可以试试下面的css,看看它是否有效。
.main_content {
width: 100%;
height: 400px;
font-weight: 800;
}
.main_content>* {
border: 1px solid red;
display: table;
margin: 0 auto;
margin-bottom: 30px;
text-align: center;
}
<div class="first_article">
<div class="first_content">
<div class="main_content">
<span class="growth">Growth</span>
<h2>5 compelling user referral campaign examples</h2>
<p>Jumpstarts your user referral engine with these 5 approaches toreferral campaigns from popular apps.
</p>
<h6>Author</h6>
</div>
</div>
</div>
关于javascript - 如何使用其中的文本大小调整 div 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61840422/