Dawid Zbiński Dawid Zbiński - 13 days ago 5
CSS Question

CSS element getting dimension of itself base on content

I know that this is something we would use JavaScript for, but I was wondering if it's possible or planned in next releases of CSS maybe.

I'm working on a little platform and there's a lot of relative/absolute positions. Content is dynamic so it's not a best solution to specify the static width and elements must be centered somehow. I made it possible with almost no display-errors using CSS only, but it would be great if there is something like

this
in css.

Today's code (SASS):

element
position: absolute
top: 100px
right: 50%
margin-right: -50px (static width in %/px/em/rem/...)


Something I was thinking about:

element
position: absolute
top: 100px
right: calc(50% - this.width / 2)


So, to not make this question too broad. Do you know some way to implement this kind of behavior in today's CSS? And if not, do you know if there are some plans to implement it in feature releases?

Answer

No, it is not possible today, to reference a property of it self.

Will it come? .. Hope so

In your particular sample, centering an absolute positioned div that has dynamic content, you can use transform: translate

Side note: CSS has a lot of properties, where, when combined, one can still achieve similar effect, as with below sample

div {
  position: absolute;
  top: 100px;
  border: 1px solid;
  right: 50%;
  transform: translateX(50%);
}
<div>Centered with dynamic content</div>

Comments