Is it possible to get a negative value with CSS calc()?

爷,独闯天下 提交于 2019-12-02 23:31:31

Yes, this is possible, to a point. The crucial part is to set the width of the element to 100vw then offset it by negative half the viewport width plus half the width of the centered element using, e.g. calc(-50vw + 200px):

Demo Fiddle

Given the HTML

<div id='center'>center
    <div id='full'>full width</div>
</div>

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
    text-align:center;
    position:relative;
}
#center {
    width:400px;
    height:100%;
    background:red;
    margin:0 auto;
}
#full {
    width:100vw;
    height:100px;
    background:green;
    margin-left:calc(-50vw + 200px);
}

EDIT: A simpler trick than previous ones: calc(0px - something) - with an unit - works while calc(0 - something) doesn't. See Fiddle 3

These "tricks" work:

calc(1px - something - 1px);
calc(-1 * something)
calc(0px - something) /* new */

where 0 - something didn't (at least with your example).

Fiddle 1
Fiddle 2

I have another possible solution. You can devide by -2, so you'll get a negative Result

.widest{
  margin-left: calc( (100vw - 960px) / -2 );
}

You could try next solution

.some-class {
   margin-left: calc(-1px - ((100vw - 100%) / 2) + 1px);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!