css在页面上画一个正方形,边长为页面宽度的一半

.square {
  width: 50vw;
  height: 50vw;
  background-color: /* Your color here */; /* Example: #f00 for red */
}

Explanation:

  • width: 50vw;: This sets the width of the square to 50% of the viewport width (vw stands for viewport width).
  • height: 50vw;: This sets the height of the square to 50% of the viewport width, making it a square since width and height are equal.
  • background-color: /* Your color here */;: This sets the background color of the square. Replace /* Your color here */ with your desired color value (e.g., a named color like red, a hexadecimal value like #f00, an RGB value like rgb(255, 0, 0), or an HSL value).

How to use it in your HTML:

<!DOCTYPE html>
<html>
<head>
<title>Square Example</title>
<style>
.square {
  width: 50vw;
  height: 50vw;
  background-color: blue; /* Example: blue */
}
</style>
</head>
<body>

<div class="square"></div>

</body>
</html>

This HTML creates a div element with the class "square". The CSS rules will apply to this div, creating a square that's half the width of the viewport.

Alternative using aspect-ratio (modern browsers):

For modern browsers that support the aspect-ratio property, you can use this cleaner approach:

.square {
  width: 50vw;
  aspect-ratio: 1 / 1;
  background-color: /* Your color here */;
}

This sets the width to 50vw and then uses aspect-ratio: 1 / 1 to maintain a 1:1 aspect ratio, ensuring it's always a square. This is generally preferred as it's more concise and handles resizing more gracefully. However, be mindful of browser compatibility if you need to support older browsers.

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