有没有办法在CSS中创建这样的按钮?带有“博客”文字的。我尝试在每个角落添加一个 div,给这些 div 边框并旋转它们,但正如你所看到的(Anout Me btn),这不是最好的解决方案,因为角落不准确。
谢谢您的想法!
没有 CSS 规则可以做到这一点,但这是可能的。您的按钮需要一个
inline-block
或 block
元素,并且左侧和右侧都有边框。然后,您需要在容器的顶部和底部放置(使用 absolute
定位)两个伪元素 ::before
和 ::after
。只需添加透视图并相应地旋转元素的 X 值即可。它可能不是在每台设备上都是“像素完美”的,但在最新的设备和浏览器上它看起来近乎完美。
您可以看看我不久前制作的这些六边形按钮以获得更好的想法:https://codepen.io/chriskirknielsen/pen/MpXKVV
编辑:这是一个代码片段,而不是 Codepen 链接:
*, *::before, *::after {
padding: 0;
margin: 0;
box-sizing: border-box;
transition: .25s all .02s ease-in-out;
}
body, html {
text-align: center;
font-family: sans-serif;
font-size: 32px;
background-color: #123143;
height: 100%;
}
.button--hexagon {
position: relative;
margin: 1rem auto;
text-align: center;
font-size: .5rem;
line-height: .5rem;
vertical-align: middle;
color: #ffce00;
display: inline-block;
border-width: 0;
border-style: solid;
border-color: #ffffff;
padding: .5rem;
cursor: pointer;
background: transparent;
width: calc(100% / 6);
}
.button--hexagon span {
z-index: 20;
position: relative;
}
.button--hexagon::before, .button--hexagon::after {
content: '';
position: absolute;
border-color: inherit;
border-style: inherit;
height: 50%;
width: 100%;
left: 0;
z-index: 10;
background-color: rgba(18, 49, 67, 0.75);
}
.button--hexagon::before {
border-width: 2px 2px 0 2px;
top: 0;
transform-origin: center bottom;
transform: perspective(0.5rem) rotateX(3deg);
}
.button--hexagon::after {
border-width: 0 2px 2px 2px;
bottom: 0;
transform-origin: center top;
transform: perspective(0.5rem) rotateX(-3deg);
}
.button--hexagon:hover {
color: #123143;
border-color: #ffce00;
}
.button--hexagon:hover::before,
.button--hexagon:hover::after {
background: #ffce00;
}
<button class="button--hexagon"><span>Some text</span></button>
CSS 并不容易做到这一点。您可以尝试使用 CSS 形状来获得粗略的相似性 - 但作为形状,您将无法获得准确的结果,并且如果您的意图是这样,您可能无法在其上画出正确的笔画。
#octagon {
width: 100px;
height: 100px;
background: red;
position: relative;
}
#octagon:before {
content: "";
position: absolute;
top: 0;
left: 0;
border-bottom: 29px solid red;
border-left: 29px solid #eee;
border-right: 29px solid #eee;
width: 42px;
height: 0;
}
#octagon:after {
content: "";
position: absolute;
bottom: 0;
left: 0;
border-top: 29px solid red;
border-left: 29px solid #eee;
border-right: 29px solid #eee;
width: 42px;
height: 0;
}
您可以在纯CSS中使用clip-path属性
button {
width: 200px;
min-height: 50px;
clip-path: polygon(6% 0, 93% 0, 100% 22%, 100% 78%, 94% 98%, 7% 98%, 0 79%, 0 21%);
background: green;
}
和按钮
<button>Cut corner effect.</button>