我想缩进段落的第一行(这正是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>

推荐答案

以下是一个需要额外包装的黑客 idea :

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>

Html相关问答推荐

动态FormControl值在Angular 上绑定错误的问题

未在抖动中播放的HTML音频||文本正在工作其他标记正在播放,但音频未播放

Style=背景图像URL引用变成&;Quot;

从网页中提取URL

如何从elementor中的滑块中获取文本?

如何在css中在span中绘制圆弧?

在 HTML 视频上环绕文本叠加

如何为卡片块制作侧丝带样式

如何在Rmarkdown中添加千位分隔符?

水平填充容器内的空间

如何只为 Navbar 中的一个元素提供动画,其余元素没有使用 css 的动画

如何在 Flex 对齐内容框下显示隐藏按钮和文本

使用 calc 函数设置字体大小时 Flexbox 项目重叠

如何让一个 div 始终贴在容器的边缘?

如何在 css 和 html 中创建花状 struct

如何将图像移动到父容器的右侧?

防止 HTML 表格在 Quarto 中使用全页宽度

让 Bootstrap 5 模式和背景占据父容器的宽度和高度,而不是全屏

用 flexbox 和 overflow 覆盖

图标未定位到右上角