如何在css属性中使用加/减? [英] How to use add/subtract in css propert?
问题描述
如何在css属性中添加/减去?
#box {
position:absolute;
top:50%;
left:calc(50% - 286px);
margin-left:-75px / *宽度的一半* /
background-color:red; / *或更有用的东西* /
z-index:100;
}
我只是试图在实际顶部添加/左百分比
top:50% - contents_height_in_number_with_px
我想这样做,我的主要内容自动居中
注意:我已经在google上搜索,并且已经尝试calc()没有找到任何解决方案解决方案css(
calc()
)不支持所有浏览器。您需要知道当前视口的高度和div#框的高度。这里有一种确定两者的方法,即将元素居中。你可以沟通top:50%;
<$ c $ <$ p $ <$ p $ c> // 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} ;
}
//中心一个元素(使用视口函数)
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;
}
//用法:
center(document.getElementById('box'));
另请参阅 this jsfiddle
How to add/subtract in css property?
#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; }
I am simply try to add/subtract the contents value in the actual top and left percentage
top: 50% - contents_height_in_number_with_px
I want to do this so that my main contents is automatically centered Note:i already search on googled and already try calc() not found any solution
解决方案That css (
calc()
) is not supported in all browsers. You need to know the height of the current viewport and the height of div#box. Here's a way to determine both, i.e. to center an element. You can ditchtop:50% ; left:calc(50% - 286px);margin-left:-75px
in the css now.// 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'));
See also this jsfiddle
这篇关于如何在css属性中使用加/减?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!