Html 换行时在 DIV 中缩进文本的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/480567/
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
What is the best way to indent text in a DIV when it wraps?
提问by fetucine53
So I have a DIV that contains some dynamic text. Let's say I know the text and font-size but I don't know the size of the DIV. I'd like the display of the text in the DIV to be intelligent enough to show indentation when text wraps.
所以我有一个包含一些动态文本的 DIV。假设我知道文本和字体大小,但我不知道 DIV 的大小。我希望 DIV 中的文本显示足够智能,以便在文本换行时显示缩进。
Say my original text looked something like this:
假设我的原始文本看起来像这样:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
Instead, I want it to look like this:
相反,我希望它看起来像这样:
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt
What's the best way to do this if I don't know the size of the DIV a priori? And what's the best way to do it if I do know the size?
如果我不知道 DIV 先验的大小,最好的方法是什么?如果我知道尺寸,最好的方法是什么?
Thanks!
谢谢!
回答by Allain Lalonde
If I understand what you're asking for, this works for me:
如果我理解你的要求,这对我有用:
div {
padding-left: 2em;
text-indent: -2em;
}
回答by Sampson
Not sure of the cross-browser support, but you could use the first-line pseudo-element:
不确定跨浏览器支持,但您可以使用第一行伪元素:
p {padding:10px;}
p:first-line {padding-left:0px;}
<p>Hello World, I'm Jonathan Sampson</p>
Would be diplayed as
将被显示为
Hello World I'm
Jonathan
Sampson
你好世界我是
乔纳森
桑普森
Other than that, you could give the element left-padding, and then a negative text-indent.
除此之外,您可以给元素左填充,然后是负文本缩进。
回答by jpsimard-nyx
回答by Noldorin
This should work equally well for both variable and fixed size DIVs.
这对于可变和固定大小的 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>
回答by Razvan Zamfir
Use the CSS text-indent
property:
使用 CSStext-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>