最佳答案
使用 CSS 转换:
您可以使用两个伪元素和 CSS 旋转变换来创建菱形,如下面的代码片段所示。这将使文本不受转换的影响,因此定位它会相对容易。
rotateZ(45deg)
生成具有相等边的菱形,而额外的 rotateX(45deg)
负责拉伸(stretch)外观,使边看起来像它们一样不等长。
文字定位比较简单,只需要居中对齐,然后设置line-height
与容器的height
相同即可.请注意,这种垂直居中的方法仅适用于文本位于单行中的情况。如果它可以跨越多行,那么它应该放在一个额外的元素中,并且 translateY(-50%)
转换应该用于垂直居中。
.diamond {
position: relative;
height: 200px;
width: 200px;
line-height: 200px;
text-align: center;
margin: 10px 40px;
}
.diamond:before {
position: absolute;
content: '';
top: 0px;
left: 0px;
height: 100%;
width: 100%;
transform: rotateX(45deg) rotateZ(45deg);
box-shadow: 0px 0px 12px gray;
}
.diamond:after {
position: absolute;
top: 10px;
left: 10px;
content: '';
height: calc(100% - 22px); /* -22px is 2 * 10px gap on either side - 2px border on either side */
width: calc(100% - 22px); /* -22px is 2 * 10px gap on either side - 2px border on either side */
border: 1px solid orange;
transform: rotateX(45deg) rotateZ(45deg);
}
<div class='diamond'>
Text Here
</div>
使用 SVG:
可以使用 SVG path
元素代替 CSS 转换来创建相同的形状。以下代码段中提供了示例。
.diamond {
position: relative;
height: 200px;
width: 300px;
line-height: 200px;
text-align: center;
}
.diamond svg {
position: absolute;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
z-index: -1;
}
path.outer {
fill: white;
stroke: transparent;
-webkit-filter: url(#dropshadow);
filter: url(#dropshadow);
}
path.inner {
fill: transparent;
stroke: orange;
}
<div class='diamond'>
<svg viewBox='0 0 100 100' preserveAspectRatio='none'>
<filter id="dropshadow" height="125%">
<feGaussianBlur in="SourceAlpha" stdDeviation="1" />
<feOffset dx="0" dy="0" result="offsetblur" />
<feMerge>
<feMergeNode/>
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
<path d='M2,50 50,2 98,50 50,98z' class='outer' />
<path d='M8,50 50,8 92,50 50,92z' class='inner' />
</svg>
Text Here
</div>
<!-- Filter Code Adopted from http://stackoverflow.com/questions/6088409/svg-drop-shadow-using-css3 -->
关于html - 我如何使用 CSS 在菱形内创建标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594522/