4

I would like to make one of my CSS property proportional to another, but none is parent of the other one. It would looks like this:

elem-to-look {
    /**
     * This value could not be explicit,
     * And I want it to working even with default values.
     */
    width: 50px;
}

elem-derivative {
    /* I'm looking for something like this */
    left: [elem-to-look: width] + 25px;
}

Is it even possible ? If no, what kind of solution would you advise me ?

5
  • 2
    Look into SASS or LESS they allow variables and bunch of other stuff to help build your CSS. Commented Jun 29, 2015 at 8:11
  • 1
    But even those arent live, meaning they compile and then values remain static.. and live version i think is too heavy Commented Jun 29, 2015 at 8:13
  • 1
    Using pure CSS you could use calc, but only if you know the width of the element, which can be relative: elem-to-look { width: 50%; } and elem-derivative { left: calc(50% + 25px)}. Commented Jun 29, 2015 at 8:14
  • There is serious need for css lib that is like jquery for css. (Lots of common sense functionality ) Commented Jun 29, 2015 at 8:15
  • css variables are only supported by FF Commented Jun 29, 2015 at 8:28

1 Answer 1

1

Well, it is hard, but under some conditions you can do that.

If your body font-size is stable and you don't change it in parents of your elements, you can do the following:

body {
    font-size: 20px;
}

elem-to-look {
    width: 2.5em;
}

elem-derivative {
    left: calc(2.5em + 25px);
}

If this satisfies you, that could work.

Sign up to request clarification or add additional context in comments.

4 Comments

That is what I also suggested in my comment. He must somehow generate the width for elem-to-look, by hand or by script, and knowing this value is everything you need.
Well, that is not really it. You proposed to use 50% of the parent element, what I propose is to use the font-size which is much more flexible just because you don't care about its parents. From the question I assume they don't have the same parent.
I assumed a relative declaration, I didn't propose to use exactly 50%. And yes, I assumed the both elements are siblings.
Anyway it seems we both don't satisfy that guy :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.