What is the best way to indent text in a DIV when it wraps?

混江龙づ霸主 提交于 2019-12-20 09:29:48

问题


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.

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?

Thanks!


回答1:


If I understand what you're asking for, this works for me:

div {
    padding-left: 2em;
    text-indent: -2em;
}



回答2:


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.




回答3:


W3C says you just have to use text-indent property.

source

.indentedtext
{
    text-align:start;
    text-indent:5em;
}



回答4:


This should work equally well for both variable and fixed size DIVs.

<div style="width: 150px; text-indent: -2em; padding-left: 2em;">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
    incididunt.
</div>



回答5:


Use the CSS text-indent property:

.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>


来源:https://stackoverflow.com/questions/480567/what-is-the-best-way-to-indent-text-in-a-div-when-it-wraps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!