-1

I'm building some global button classes for a CSS framework, and I'm wondering if there's any way to set an element's width to be the same as the height without hard-coding it.

Here's an example of how it would work:

HTML

<button class="button square-button">OK</button>

<div class="container">
    <button class="button large-button square-button">OK</button>
</div>

CSS

.button {
    height: 50px;
    padding: 0 20px;
}

.square-button {
    width: (always-same-as-height);
    padding: 0; // Disable padding so it becomes a square
}

...

.container {
    height: 100px

    .button {
          height: inherit;
    }
}

In some scenarios I want to be able to set the height depending on the container height, and have all the buttons with the square-button class dynamically resize to that height while still staying a perfect square shape.

Is this possible using only CSS?

Swen
  • 767
  • 1
  • 9
  • 31
  • 1
    Not really possible with pure CSS, it could be worthwhile looking at a tool such as SASS as it allows you to create variables. – snack_overflow Nov 08 '18 at 16:58
  • How exaclty will a preprocessor know what the element's `width` will be, @snack? The requirement was: *"without hard-coding"*. Variables are just a fancy way of hard-coding, because you hard-copy in one place and it gets applied everywhere you used it. OP seems to want a solution which adapts to current element `width`, using CSS. – tao Nov 08 '18 at 19:30
  • I wasn't able to find a proper definition for *"pure CSS"*. Can you please help me out on this one? Providing an example of *"impure CSS"* will do just fine, as long as it helps clear the confusion. – tao Nov 08 '18 at 19:35

1 Answers1

-1

You can make use of CSS variables modules to achieve that. However, the browser support for CSS variables is not so good. So, proceed with caution by first checking if the browser versions you wish to support have implemented CSS modules or not.

Kaashan
  • 352
  • 3
  • 12