我想在我的第一个div元素中心设置我的第二个div元素。我想不知怎的,我设法让它居中。但我认为我犯了一些错误,在我看来它没有正确居中,而且这种JavaScript风格在我看来也很糟糕。有没有更好的方法呢?我的JavaScript代码是否正确?
HTML
<div class='first'>
<div class='second'>
</div>
</div>
的JavaScript
var first = document.getElementsByClassName('first')[0];
var second = document.getElementsByClassName('second')[0];
var height = first.offsetHeight;
second.style.width = height/2+"px";
second.style.height = height/2+"px";
second.style.marginLeft = height/4+"px";
second.style.marginTop = height/4+"px";
答案 0 :(得分:1)
理由是 3px
,这就是为什么不进行定位,但是你将2.1结果除以需要。
var first = document.getElementsByClassName('first')[0];
var second = document.getElementsByClassName('second')[0];
var height = first.offsetHeight;
second.style.width = height/2.1+"px";
second.style.height = height/2.1+"px";
second.style.marginLeft = height/4+"px";
second.style.marginTop = height/4+"px";
答案 1 :(得分:1)
offsetHeight
将获得包含边框的元素的高度,clientHeight
赢了。而不是:
var height = first.offsetHeight;
尝试:
var height = first.clientHeight;
我还使用top
和left
与position:absolute
进行定位,因为这会将元素排除在页面流之外,我认为这是您正在寻找的行为对
参考文献:
(按照链接查看盒子模型图)
答案 2 :(得分:0)
var second = document.getElementsByClassName('second')[0];` var left =(screen.width / 2) - (100/2); var top =(screen.height / 2) - (100/2); second.style.width =“100px”; //根据您的要求设置 second.style.height =“100px”; //根据您的要求设置 second.style.left = left +“px”; second.style.top = top +“px”;
答案 3 :(得分:0)
为了以防万一,你感兴趣,我试图想出一个仅限CSS的解决方案。
http://jsfiddle.net/53M6A/1/ 这是我对.second类所做的更改。
.second{
left: 50%; //move 50% to left
top: 50%; // move 50% down
margin-left: -50px; //move half of it's own size back to the left
margin-top: -50px; //move half of it's own size back to the top
position: relative; //make it relative, so it can be moved around by left/top
width:100px;
height:100px;
background: #fff;
border-radius:50%;
}
答案 4 :(得分:0)
我一直在玩你的小提琴,最后,我改变了你的最后两行:
first.style.display = "table-cell";
first.style.verticalAlign = "middle";
second.style.margin = "0 auto";
似乎完全集中于我。