Reputation: 24053
I am trying to do something like this:
.my-style {
width: 50px;
margin-left: calc(50% - calc(width / 2));
}
Later I am changing the width to 90px and I want the margin grow accordingly.
It doesn't work. Is it possible?
Upvotes: 4
Views: 21833
Reputation: 1
.my-style {
width: 50px;
margin-left: calc(100% - calc(width / 2));
}
Try like this, it worked wonder for me.
Upvotes: -2
Reputation: 8085
The newest browser's SHOULD support it, I tried the following code.
This is a webkit example I made, so check it in chrome
CSS
p {
-webkit-var-a: -webkit-calc(1px + 3px);
margin-left:-webkit-calc(-webkit-var(a) + 5px);
}
HTML
<p>This text should have margin-left, but it doesn't</p>
FIDDLE
If you inspect the <p>
element you can see that it DOES see the code as valid, it just doesn't do anything... So it seems that for now you have to use javascript, LESS or anything equivelent as it's still a experimental feature.
EDIT:
it DOES seem to work when you make the var a plain number:
p {
-webkit-var-a: 3px;
margin-left:-webkit-calc(-webkit-var(a) + 5px);
}
So to answer your question, yes this is possible, but I would not recommend it for now.
CSS
.my-style {
height:100px;
background-color:black;
-webkit-var-width: 50px;
margin-left: -webkit-calc(50% - -webkit-var(width) / 2);
}
FIDDLE
Upvotes: 4
Reputation: 52922
You can't do something like that with standard CSS, you should investigate an alternative such as LESS
Edit: I was wrong, CSS3 supports this if you use var() within calc():
.my-style {
width: 50px;
margin-left: calc(50% - (var(width) / 2));
}
I think should do it.
Upvotes: 1