How To Set Height Equal To Width Css

CSS Programming

Have you ever wanted to set the height of an element equal to its width using CSS? Well, I’m here to show you how to do just that! It’s a technique that can come in handy in various situations, such as creating square elements or maintaining aspect ratios for images. In this article, I’ll guide you through the steps to achieve this effect.

Understanding the CSS Box Model

Before we dive into the specifics of setting the height equal to the width, let’s first understand the CSS box model. When we set the width and height of an element using CSS, we’re actually setting the dimensions of the content box. However, each element also has additional space around it, including padding, border, and margin. To set the height equal to the width, we need to consider all these aspects of the box model.

Using Percentage-Based Padding

One way to set the height of an element equal to its width is by using percentage-based padding. By setting the top or bottom padding as a percentage of the width, we can make the height of the element responsive to changes in its width.

.square-element {
width: 100%;
padding-top: 100%;

By setting both the width and padding-top to 100%, we ensure that the element maintains a square shape, as the height will always be equal to the width. Remember to adjust the padding as needed to achieve the desired aspect ratio.

Flexbox Approach

Another approach to setting the height equal to the width is by using CSS flexbox. Flexbox provides a powerful way to create flexible layouts, and it can be particularly useful for achieving equal height and width.

.container {
display: flex;

.square-element {
flex: 1;
aspect-ratio: 1/1;

In the code above, we create a flex container and set the square element to have a flex value of 1, which allows it to grow and shrink to fill the available space. We also use the aspect-ratio property to maintain a square shape.


Setting the height equal to the width using CSS can be a valuable technique to create visually appealing layouts and maintain aspect ratios. In this article, we explored two approaches: using percentage-based padding and utilizing CSS flexbox. Depending on your specific use case, one method may be more suitable than the other.

Remember to always test your code across different devices and screen sizes to ensure a consistent user experience. Happy coding!