0

I tried to use left:calc(width:/2); but it didn't work. is there any way to use "calc" to controll the left and right css properties?

I also tried using webkit, but it didn't work.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
MagicArcher
  • 17
  • 1
  • 2

1 Answers1

1

Thats just simply not how calc works and is supposed to be used. calc is used to calculate an amount based on multiple units, not based on multiple css properties.

For example, you cant calculate the left based directly on the width.

However what you can do is for example something like this:

element {
  width: 78%;
  left: calc(78% / 2);
}

Here you just manually copy the value of the width and divide it by 2 however, since its always 78% at any time, you might aswell just replace it with this:

element {
  width: 78%;
  left: 39%;
}

This might confuse you since then there isnt really a need for calc() however there is one really really important feature of calc where it is usefull.

That feature is the ability to calculate absolute units like px together with relative units like % or vw

A practical example:

Lets say you have a site that contains 2 divs that vertically lay on top of eachother. The top one will be the header and the bottom one might be the content of the page.

Lets say you want the header to be always 50px high, you could then define the header like this:

#header {
  height: 50px
}

Then you want the content to be the rest of the page, which will be the window height (100vh) subtracted by 50px that is taken by the header, the height of the content element should then be 100vh - 50px which can be calculated using calc() like this:

#content {
  height: calc(100vh - 5px);
}

So simply put: the reason your css didnt work is because you misunderstood how and what css calc() is used for.

Note: keep in mind to always put spaces around the operators in the calc function, else it will simply not work.

So this will work:

calc(100% - 50px);

But this wont work:

calc(100%-50px);
Luke_
  • 745
  • 10
  • 23
  • Thanks for giving time. I was looking for "Calc" because "width" value is not constant. I had "div" with a picture on middle. I wanted to make it always in middle. even with media queries I needed to way to calculate. – MagicArcher Oct 16 '20 at 12:57
  • but calc method still not working. I tried 50% / 2 but didn't work – MagicArcher Oct 16 '20 at 12:59
  • You didnt read my question properly, you shouldnt use calc() on values that can be manually calculated, 50% / 2 is 25% – Luke_ Oct 16 '20 at 13:00
  • Cant you setup a codepen so i can look at what you did wrong exactly? – Luke_ Oct 16 '20 at 13:02
  • Yeah you right. is there any way? I mean width is not constant. – MagicArcher Oct 16 '20 at 13:02
  • yes there is a way, you could just make the width of the div 100vw to make it as wide as the whole browser, and then use `text-align: center` on that div, to align the image in the center within that div – Luke_ Oct 16 '20 at 13:04