所以,我想做一个 H1 标签来绕过一个容器。如果我使用 CSS 旋转,我可以旋转文本,但显然只能旋转 90 度,而不是围绕一个 div。我希望将文本保留在一个 H1 标签中,因为设计师希望它成为页面的标题并用于 SEO 目的。
根据我所做的所有研究,我不确定这是否可行。我有点难过。我想你们会知道这是否可能。
<h1>Latest News</h1>
<div>Blue Square</div>
最佳答案
- 放置您的盒子
relative
(有一些margin
空间用于 offset 标题文本) - 定位您的标题
absolute
负顶-1.1em
- 创建
<span>
(在标题内)用于旋转的垂直文本 - 将您的 SPAN absolute 放在右边
100% + 1.1em
-
transform
在原点旋转你的SPANright top
通过-90deg
/*QuickReset*/*{margin:0;box-sizing:border-box;}html,body{min-height:100%;font:14px/1.4 sans-serif;}
.box {
position: relative;
margin: 3em;
width: 140px;
height: 100px;
background: #0bf;
}
.box h1 {
position: absolute;
text-transform: uppercase;
white-space: nowrap;
font-size: 2em; /* play only with this value. don't touch the rest! */
top: -1.1em;
}
.box h1 span{
position: absolute;
top: 0.35em;
right: calc(100% + 1.1em);
transform-origin: right top;
transform: rotate(-90deg);
}
<div class="box">
<h1><span>Latest</span> News</h1>
</div>
<div class="box">
<h1><span>Special</span> Offers!</h1>
</div>
<div class="box">
<h1><span>Edge case with</span> some long text</h1>
</div>
包装成<span>
自动(服务器端)
如果您要提取未知长度的标题,即从 CMS,我建议您将字符串分成两半 - word-aware!为了确定需要包裹在 span
中的前半部分
使用 PHP 的示例:
<?php
/**
* Wrap first half of a sentence into <span>, word-aware!
*/
function span_first_half($s) {
$n = floor(strlen($s)/2);
preg_match(("/.{{$n}}\\S*/"), $s, $a);
$b = substr($s, strlen($a[0]));
return "<span>$a[0]</span>$b";
}
PHP - 像这样使用:
<h1><?= span_first_half("Edge case with some long text") ?></h1>
<h1><?= span_first_half("This is cool!") ?></h1>
将导致:
<h1><span>Edge case with</span> some long text</h1>
<h1><span>This is</span> cool!</h1>
JavaScript - 像这样使用
function span_first_half(s) {
const n = Math.floor(s.length/2),
a = s.match(RegExp(".{"+n+"}\\S*"))[0],
b = s.substr(a.length);
return `<span>${a}</span>${b}`;
}
console.log( span_first_half("Edge case with some long text") );
console.log( span_first_half("This is cool!") );
以上演示改编自this JavaScript example
关于DIV Angular 周围的 HTML/CSS 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55112548/