I want the left
css property to take the value from the html element using attr
like this
<div left-value="30px"/>
div{
left: attr(left-value);
}
is this even possible? it works with after and before.
CodePudding user response:
The attr css function is appearently very powerful but yet very limited as described here:
https://developer.mozilla.org/en-US/docs/Web/CSS/attr
Note: The attr() function can be used with any CSS property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse.
Anyway there's a trick you can use to get quite the same result but using css custom properties. Instead of defining an attribute on the html element that you are going to read in your css rule using attr
, you can just set that same value on a custom property using the inline styling. Then in your rule just use that custom property to set the left properrty of the element.
Here I also put a container with position relative, to better highlight the correct working of this solution:
.container{
position: relative;
border: dashed 4px lightgray;
height: 100vh;
width: 100vw;
}
.container > div{
position: absolute;
left: var(--left-value);
border: solid 1px gray;
background: red;
width: 20px;
height: 20px;
}
<div >
<div style="--left-value: 20px;"></div>
</div>
Of course it doesn't look very smart to use a custom property instead of using directly the left property since you are using the inline styling already. There are cases when this solution could be the way to go.. but here indeed it's not really changing the game
CodePudding user response:
First-of-all there is no such attribute as left-value in HTML. You have to use pre-build attr in HTML cuzz it's not react. Secondly if you want to left align the just simply use position and left attr of css or just do some styling using margin-left.