用css画一个五边形和一个六边形

<!DOCTYPE html>
<html>
<head>
<style>
.pentagon {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
}
.pentagon::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 70px solid red; /* Adjust this value to control pentagon shape */
}
.pentagon::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 70px solid red; /* Adjust this value to control pentagon shape */
}



.hexagon {
  width: 100px;
  height: 55px;
  background: blue;
  position: relative;
}
.hexagon::before {
  content: "";
  position: absolute;
  top: -25px; /* Half of the height */
  left: 0;
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-bottom: 25px solid blue;
}
.hexagon::after {
  content: "";
  position: absolute;
  bottom: -25px; /* Half of the height */
  left: 0;
  width: 0;
  height: 0;
  border-left: 50px solid transparent;
  border-right: 50px solid transparent;
  border-top: 25px solid blue;
}
</style>
</head>
<body>

<div class="pentagon"></div>
<br>
<div class="hexagon"></div>

</body>
</html>

This code creates a pentagon and a hexagon using CSS. Here's how it works:

  • Pentagon: It uses ::before and ::after pseudo-elements to create triangles on the top and bottom of a square, forming the pentagon shape. The border-bottom and border-top values control the pentagon's shape. Adjusting the 70px value will change the angles.

  • Hexagon: Similar to the pentagon, it uses ::before and ::after to add triangles to the top and bottom of a rectangle. The height of the rectangle and the triangles are carefully calculated to create the hexagon.

This is a common and relatively simple method for creating these shapes with pure CSS. You can adjust the colors and sizes as needed. For more complex polygons, using tools like Clippy or SVG might be more efficient.

posted @ 2024-12-03 09:14  王铁柱6  阅读(135)  评论(0)    收藏  举报