如果一个段落的第一行跨越多行,那么仅对第一行进行缩进。

3

我希望缩进段落的第一行(就像 text-indent CSS 属性所做的那样),但只对多行的段落进行操作。如果段落只有一行,我不想将其缩进。

是否有类似的解决方法?

p {
 text-indent: 20px;
 max-width: 350px;
}
<p>This is a pretty long paragraph which spans over a few lines. For that reason I wish its first line to be indented (as it should be).</p>

<p>These are short paragraphs.</p>

<p>I don't want them indented.</p>

<p>Unless they take multiple lines.</p>


我不认为仅凭 CSS 就能实现这一点——我不相信在任何情况下都有很好的支持来进行条件定位。但也许比我更聪明的人会为您提供解决方案。 - Alexander Nied
1个回答

2

这里有一个需要额外包装的折衷主意:

p {
 max-width: 350px;
 line-height:1.2em; /* height of one line */
}
.e {
  display:flex; /* a flex container to be able to use 100% in the height*/
}
/* a pseudo element to create the indentation*/
.e p:before {
  content:"";
  float:left;
  width:20px; 
  /* 0px if 100% (height of p) is less or equal to 1.2em (one line)
     1px if 100% is bigger than one line
  */
  height:clamp(0px,100% - 1.2em,1px)
}
<div class="e"><p>This is a pretty long paragraph which spans over a few lines. For that reason I wish its first line to be indented (as it should be).</p></div>

<div class="e"><p>These are short paragraphs.</p></div>

<div class="e"><p>I don't want them indented.</p></div>

<div class="e"><p>Unless they take multiple lines.</p></div>

一个互动演示,您可以调整大小以查看其神奇之处:

p {
 line-height:1.2em; /* height of one line */
}
.e {
  display:flex; /* a flex container to be able to use 100% in the height*/
  overflow:hidden;
  border:1px solid;
  resize:horizontal;
  width: 350px;
}
/* a pseudo element to create the indentation*/
.e p:before {
  content:"";
  float:left;
  width:20px; 
  /* 0px if 100% (height of p) is less or equal to 1.2em (one line)
     1px if 100% is bigger than one line
  */
  height:clamp(0px,100% - 1.2em,1px)
}
<div class="e"><p>This is a pretty long paragraph which spans over a few lines. For that reason I wish its first line to be indented (as it should be).</p></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接