跨度元素带有宽度和换行符。

4

我从API接收到的内容包含多个元素,后面跟着未标记的文本。

例如:

<span>1</span> Some text. <span>2</span> Some text.

我希望这些span元素能够有一个预设的宽度并且在前面加上一个换行。
例如:
 1 Some text.

 2 Some text.

"display: block" 对于 spans 元素来说允许使用 width 属性,但同时也会在每个 span 元素后面创建一个断点。

"display: inline-block" 也允许使用 width 属性,但我无法找到如何在其前面创建换行符的方法。

将 spans 元素保留为 "display: inline" 可以在每个 span 元素前面创建换行符(使用 ::before content)。然而,你不能为内联元素指定 width 属性(至少我没有看到过)。


我不确定这里是否有一个实际的问题。据我所知,选项三(“display: inline”不允许使用宽度属性,但我可以通过伪类before content产生换行)可以实现您所需的功能。到底有什么问题? - Alexander Nied
2个回答

5
为了达到预期的结果,请使用以下内容和空白选项。

span::before {
  content: "\A";
  white-space: pre;
}
<span>1</span> Some text. <span>2</span> Some text.

codepen - https://codepen.io/nagasai/pen/RdmxrR


0
如果您有此内容的包装器,您可以将其设为网格容器,轻松实现您想要的效果:

.wrapper {
  display:grid;
  grid-template-columns:30px 1fr;
}

span {
 text-align:center;
 outline:1px solid green;
}
<div class="wrapper">
<span>1</span> Some text. <span>2</span> Some text.
</div>

使用flexbox和display:contentshttps://caniuse.com/#feat=css-display-contents)的另一个想法。

.wrapper {
  display:flex;
  flex-wrap:wrap;
  padding-left:10px;
}

span {
 display:contents;
 outline:1px solid green;
}
/*create line break*/
span:before {
  content:"";
  flex-basis:100%;
}

/*control the width*/
span:after {
  content:"";
  width:20px;
}
<div class="wrapper">
<span>1</span> Some text. <span>2</span> Some text.
</div>

这里还有另一种使用计数器的方法:

body {
 counter-reset: count;
}

span {
  counter-increment: count;
  font-size:0; /*remove default content*/
}
/*add line break*/
span::before {
  content: "\A";
  white-space: pre;
}

/*add content with counter*/
span::after {
  content:counter(count);
  font-size:initial;
  display:inline-block;
  width:30px; /*control the width*/
  text-align:center;
}
<span>1</span> Some text. <span>2</span> Some text.


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