时间:2021-07-01 10:21:17 帮助过:37人阅读
在之前要先了解一下正六边形内角和边的关系,正六边形的每个内角是60deg,如图(√3其实是根号3):
方法一:原理把正六边形分成三部分,左中右分别是:before部分,div部分,after部分,如图:
before三角形部分是div的before伪元素,after三角形部分是div的after伪元素。
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>用css画正六边形</title>
- <style type="text/css">
- .div {
- position: relative;
- width: 50px;
- height: 86.6px;
- margin: 50px auto;
- background-color: red;
- }
- .div:before {
- content: '';
- display: block;
- position: absolute;
- width: 0;
- height: 0;
- right:50px;
- border-width: 43.3px 25px;
- border-style: solid;
- border-color: transparent red transparent transparent;
- }
- .div:after {
- content: '';
- display: block;
- position: absolute;
- width: 0;
- height: 0;
- left:50px;
- border-width: 43.3px 25px;
- border-style: solid;
- border-color: transparent transparent transparent red;
- top:0;
- }
- </style>
- </head>
- <body>
- <div class='div'></div>
- </body>
- </html>
效果图:
注意div及伪元素的宽高需要根据上面的公式计算。
方法二:也是把正六边形分成三个宽高相同的div,然后使用定位以及css3 transform:rotate分别向左右旋转60deg形成正六边形,如图:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>用css画正六边形</title>
- <style type="text/css">
- .one {
- width: 50px;
- height: 86.6px;
- margin: 0 auto;
- border-top: 1px solid red;
- border-bottom: 1px solid red;
- }
- .two {
- position: absolute;
- width: 50px;
- height: 86.6px;
- left: 25px;
- top: 0;
- transform: translate(-50%,-50%);
- transform: rotate(60deg);
- border-top: 1px solid red;
- border-bottom: 1px solid red;
- }
- .three {
- position: absolute;
- width: 50px;
- height: 86.6px;
- left: 25px;
- top: 0;
- transform: translate(-50%,-50%);
- transform: rotate(300deg);
- border-top: 1px solid red;
- border-bottom: 1px solid red;
- }
- </style>
- </head>
- <body>
- <div style='position:relative;width:100px;margin:0 auto;'>
- <div class='one'></div>
- <div class='two'></div>
- <div class='three'></div>
- </div>
- </body>
- </html>
效果图:
以上就是如何用css画正六边形?用css画正六边形的两种方法(代码实例)的详细内容,更多请关注Gxl网其它相关文章!