如何在css属性中使用加/减?

时间:2012-02-25 11:50:09

标签: javascript html css html5 css3

如何在css属性中添加/减去?

#box {
  position: absolute;
  top: 50% ;
  left: calc(50% - 286px);
  margin-left: -75px /* half of the width */
  background-color: red; /* or something more useful */
  z-index:100;
}

我只是尝试在实际的顶部和左侧百分比中添加/减去内容值

top: 50% - contents_height_in_number_with_px

我想这样做,以便我的主要内容自动居中 注意:我已经在google搜索并且已经尝试过calc()找不到任何解决方案

2 个答案:

答案 0 :(得分:3)

目前仅在IE9和Firefox 10中支持此功能。请参阅http://caniuse.com/calc

为您提供更好的解决方案可能会更少。 http://lesscss.org

如果您使用服务器端语言,您甚至可以动态解析它:

.Net:dotLESS - http://www.dotlesscss.org/ PHP:lessphp - http://leafo.net/lessphp/

.less编译为原生CSS但允许你做的比CSS通常做的更多。

答案 1 :(得分:2)

那个css(calc())是not supported in all browsers。您需要知道当前视口的高度和div #box的高度。这是一种确定两者的方法,即使元素居中。你现在可以在css中放弃top:50% ; left:calc(50% - 286px);margin-left:-75px

// get viewport dimensions
function viewport(){
    var  innerw = window.innerWidth
        ,root   = innerw  ? window : (document.body || document.documentElement)
        ,body   = (document.body || document.documentElement)
        ,which  = innerw ? 'inner' : 'client';
    return {  width : root[ which+'Width' ] 
             ,height : root[ which+'Height' ]
             ,scrollTop: body.scrollTop 
             ,scrollLeft: body.scrollLeft };
}

// center an element (uses viewport function)
function center(el){
  var dims = viewport()
     ,l = Math.floor( (0.5*dims.width)-(0.5*el.offsetWidth) )
     ,h = Math.floor( (0.5*dims.height)-(0.5*el.offsetHeight) );
  el.style.left = l+'px';
  el.style.top  = h+'px';
  return true;
}
// usage:
center(document.getElementById('box'));

另见this jsfiddle