1

is there any ways to make class add pixels to element? For example:

.block {
  height: 100px;
  width: 100px;
  background-color: red
}

.wider {
  width: calc(width + 100px);
}
<div class="block wider"></div>

So, .wider makes .block elements wider on 100px, how do I do that in the right way?

1

1 Answer 1

5

You could attempt using CSS variables and the var() function. By defining an --width variable in your .block selector then setting the width attribute of the .wider selector to be calc(var(--width) + 100px, you can achieve a class that makes the box wider. Note that in order for this to work properly you have to add an additional --width attribute to every css selector that changes the width.

div {
    width: var(--width, 100%);
}
.block {
  height: 100px;
  --width: 100px;
  background-color: red
}
.wideblock {
  height: 100px;
  --width: 200px;
  background-color: blue
}

.wider {
  width: calc(var(--width) + 100px);
}
<p>Div with just block:</p>
<div class="block"></div>
<p>Div with block and wider:</p>
<div class="block wider"></div>
<p>Div with wideblock:</p>
<div class="wideblock"></div>
<p>Div with wideblock and wider:</p>
<div class="wideblock wider"></div>

EDIT: added width: --width to all divs at the request of Temani Afif

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

4 Comments

to make this more accurate, even the original width should use the variable
I believe I have fixed it
you didn't get me, the width inside the div should be defined by the variable ... making the width:200px and then defining the variable isn't flexible, you are obliged to change both. but defining the variable and using it inside the width will make you change only the variable
Thank you for the fiddle, I believe I have fixed it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.