用css画一个平行四边形

You can create a parallelogram using CSS with the transform: skew() property. Here's a basic example:

<!DOCTYPE html>
<html>
<head>
<style>
.parallelogram {
  width: 200px;
  height: 100px;
  background-color: #007bff; /* Example color */
  transform: skewX(-20deg); /* Adjust the angle as needed */
  margin: 50px auto; /* Center the parallelogram */
}

/* Example text styling within the parallelogram */
.parallelogram p {
  color: white;
  text-align: center;
  padding-top: 20px; /* Adjust padding as needed */
  transform: skewX(20deg); /* Reverse the skew for the text */ 
}
</style>
</head>
<body>

<div class="parallelogram">
  <p>This is a parallelogram</p>
</div>

</body>
</html>

Explanation:

  • width and height: Define the dimensions of the parallelogram before the transformation.
  • background-color: Sets the color of the parallelogram.
  • transform: skewX(-20deg);: This is the key property. skewX() skews the element along the X-axis (horizontally). The value -20deg represents the angle of the skew. Positive values skew to the right, negative values to the left. You can adjust this value to control the slant.
  • margin: 50px auto;: Centers the parallelogram on the page.
  • Text inside the parallelogram: Because the parallelogram is skewed, any text inside will also be skewed. To correct this, apply an opposite skew transform to the text element (e.g., transform: skewX(20deg);). You might also need to adjust padding to position the text nicely.

Alternative approach using ::before or ::after pseudo-elements:

This approach avoids the need to reverse the skew for content inside the parallelogram:

.parallelogram {
  width: 200px;
  height: 100px;
  position: relative; /* Required for positioning pseudo-elements */
  margin: 50px auto;
}

.parallelogram::before {
  content: ''; /* Required for pseudo-elements */
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #007bff;
  transform: skewX(-20deg);
  z-index: -1; /* Place the pseudo-element behind the content */
}

.parallelogram p {
  color: white;
  text-align: center;
  padding-top: 20px;
}

This method creates a skewed pseudo-element behind the main element, giving the appearance of a parallelogram without affecting the content inside.

Choose the method that best suits your needs. The first method is simpler if you only have a background color, while the second is better if you have content within the parallelogram that you don't want skewed.

posted @ 2024-12-07 09:10  王铁柱6  阅读(98)  评论(0)    收藏  举报