所以我有一个包含一些动态文本的 DIV。假设我知道文本和字体大小,但不知道 DIV 的大小。我希望 DIV 中的文本显示足够智能,以便在文本换行时显示缩进。
假设我的原文看起来像这样:
Lorem ipsum dolor sit amet, 立面结构 elit, sed 做 eiusmod 临时事件
相反,我希望它看起来像这样:
Lorem ipsum dolor sit amet, 立面结构 elit, sed 做 eiusmod 临时事件
如果我事先不知道 DIV 的大小,最好的方法是什么?如果我知道尺寸,最好的方法是什么?
谢谢!
如果我明白你的要求,这对我有用:
div {
padding-left: 2em;
text-indent: -2em;
}
这对于可变和固定大小的 DIV 应该同样有效。
<div style="width: 150px; text-indent: -2em; padding-left: 2em;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt.
</div>
为此,只需在您的 CSS 文件中添加以下代码即可。
div {
padding-left: 2em;
text-indent: -2em;
display: inline-block;
}
<div>
Stack Overflow is a great place for
developers of all levels to come
together and help each other - as
well as other people - to solve a question!
</div>
padding-left
将在左侧尺寸上添加一些填充以缩进它。
text-indent
定义第一行缩进的缩进,因此通过将值设置为 -2
,我们将覆盖 padding-left
的值(如 2 - -2 = 0)。因此,简而言之,text-indent
将填充大小反转为 0
。
display
只会检查它的外观。有关此的更多信息,请参阅display
on MDN。
使用 CSS
text-indent
属性:
.box {
border: 1px solid #ddd;
background: #fff;
max-width: 300px;
padding: 15px 15px 15px 45px;
}
.box p {
font-family: Arial, sans-serif;
line-height: 1.5;
margin: 0;
text-align: justify;
font-size: 12px;
text-indent: -30px;
}
<div class="box">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo repellendus natus minima ex possimus? Pariatur odit distinctio, similique, adipisci nesciunt molestias iusto ipsa repellendus recusandae unde, enim veniam voluptatem expedita.</p>
</div>
div {
padding-left: 2em;
text-indent: -2em;
display: inline-block;
}
<div>
Stack Overflow is a great place for
developers of all levels to come
together and help each other - as
well as other people - to solve a question!
</div>