CSS calc()是否有可能获得负值? [英] Is it possible to get a negative value with CSS calc()?

查看:1334
本文介绍了CSS calc()是否有可能获得负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个位于视口中心的容器...

Let's say we have a container that is centered in the viewport ...

.centered{margin: 0 auto; width:960px;}

...并且在该容器中,我有另一个容器需要具有宽度视口宽度的100%。我可以将边距设置为...

... and inside that container I have another that needs to have a width of 100% the viewport width. I could set the margin to ...

.widest{margin: 0 -480px}

...。问题是值不会是-480px,但实际上是视口宽度(960px)-.centered width / 2 ... calc()都很好,很容易,只需要一个负值即可

... for example. The thing is that the value won't be -480px, but actually the viewport width (960px) - the .centered width / 2 ... all good and easy with calc(), only I need a result that is a negative value.

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

我尝试从0减去手数得到负值,但是

I've tried subtracting the lot from 0 to get a negative value, but no go.

我不想使用JS,而Webkit中只存在问题-但是与calc()无关-我的问题是,如果我将其砍死...

I don't want to use JS and I only have issues in Webkit - not with the calc() though - my problem is that if I hack it into submission by doing ...

.widest{
  margin: 0 -100%;
}

...我的页面在Chrome / Safari中横向滚动。

... my page scrolls horisontally in Chrome/Safari.

您的想法吗?

推荐答案

是的,在某种程度上是可能的。关键部分是将元素的宽度设置为 100vw ,然后使用例如,将其偏移负一半的视口宽度加上一半居中元素的宽度。 calc(-50vw + 200px)

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):

给出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);
}

这篇关于CSS calc()是否有可能获得负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆