DEV Community

Nirmal Perera
Nirmal Perera

Posted on

Idea to adding a feature for CSS

i feel like if we had an option in css to get the width of an element

example.css

:root{
    --btnWidth: getWidth('#sourceEl');
               and / or
    --btnWidth: getWidth('.sourceEl');

}
.targetEl{
    width: var(--btnWidth);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
terabytetiger profile image
Tyler V. (he/him)

I think that because you can just set both elements to the same width is the reason this doesn't need to exist?

I also feel like being able to do this would potentially introduce issues - consider this type of setup:

<div>
  <button id="sourceEl">I'm a button</button>
</div>


<style>
:root{
    --btnWidth: getWidth('#sourceEl');
}

div {
  width: var(--btnWidth);
}

button {
  width: 50%;
}
</style>

Enter fullscreen mode Exit fullscreen mode

Should the element's width be a snapshot when the page loads? Should it dynamically change? Will every browser implement the decision the same way?

You can get/set the width via JS if you wanted - but I suspect this will lead to a lot more headaches down the road, especially if you're trying to implement a mobile and desktop layout.

But the best way to find out for sure is to give it a try! πŸ§ͺ

Collapse
 
laurenceokite profile image
laurenceokite

A shared class or css variable should do just fine for this case.

Collapse
 
fabsen profile image
Fabian Weiss

Well.. JavaScript it is :D

Collapse
 
nirmal_perera_bdad62c5c3d profile image
Nirmal Perera

ya I know we can give same width using bootstrap classes. What dou you guys think about this