Span element with width and line break before
我正在从API接收内容,该API包含多个span元素,后跟未标记的文本。
示例:
1 | <span>1</span> Some text. <span>2</span> Some text. |
我希望跨度之前具有设置的宽度和换行符。
示例:
1 2 3 | 1 Some text. 2 Some text. |
跨度上的
" display:block"允许width属性,但在每个跨度之后也会创建一个中断。
" display:inline-block"允许width属性,但是我无法弄清楚之前如何创建换行符。
将跨度保留为" display:inline"可以在每个跨度之前使用换行符(使用:: before内容)。但是,不能为内联元素指定width属性(据我所知)。
要获得预期的结果,请使用下面的内容和空格选项
1 2 3 4 | span::before { content:"\\A"; white-space: pre; } |
1 | <span>1</span> Some text. <span>2</span> Some text. |
codepen-https://codepen.io/nagasai/pen/RdmxrR
如果您对此内容有package,则可以使其成为网格容器并轻松实现所需的内容:
1 2 3 4 5 6 7 8 9 | .wrapper { display:grid; grid-template-columns:30px 1fr; } span { text-align:center; outline:1px solid green; } |
1 | <span>1</span> Some text. <span>2</span> Some text. |
使用flexbox和
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | .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; } |
1 | <span>1</span> Some text. <span>2</span> Some text. |
这也是使用计数器的另一种方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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; } |
1 | <span>1</span> Some text. <span>2</span> Some text. |