使用CSS转换:
您可以使用两个伪元素和CSS旋转变换来创建菱形,如下面的代码段所示.这将使文本不受变换的影响,因此定位它将相对容易.
的rotateZ(45deg),而额外产生具有相等的边菱形rotateX(45deg)负责外观拉伸,这使得侧面看起来像它们不相等的长度.
文本定位相当简单,只需将其与中心对齐,然后将其设置为与容器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);
}Run Code Online (Sandbox Code Playgroud)
<div class='diamond'>
Text Here
</div>Run Code Online (Sandbox Code Playgroud)
使用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;
}Run Code Online (Sandbox Code Playgroud)
<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 -->Run Code Online (Sandbox Code Playgroud)