首页 > 解决方案 > 如何使我的绝对定位元素响应?

问题描述

我正在尝试将这个形状圈居中(水平和垂直)在容器中间并使其具有响应性。我不知道如何在没有绝对定位的情况下保持圆形。任何帮助表示赞赏!

var n = 20;

for (var i = 0; i < n; ++i) {
    var d = document.createElement('div');
    var r = 360 * i / n;
    var s = 'translate(200px,200px) rotate(' + r + 'deg) translate(0px, -80px)';
    
    d.setAttribute('class', 'box');
    d.setAttribute('style', '-webkit-transform:' + s);
  
    
    document.getElementById("container").appendChild(d);
}
.box {
    background: #d0d0d0;
    width: 20px;
    height: 30px;
    border-radius: 7px;
    position: absolute;
    border: 1px solid black;
}

.box:hover {
     background: red;         
}
<div id='container'></div>

http://jsfiddle.net/ths432/6qtm28f5/52/

标签: javascripthtmlcss

解决方案


将它们相对于容器定位,然后将容器居中:

var n = 20;

for (var i = 0; i < n; ++i) {
  var d = document.createElement('div');
  var r = 360 * i / n;
  var s = 'translate(-50%,-50%) rotate(' + r + 'deg) translate(0px, -80px)';

  d.setAttribute('class', 'box');
  d.setAttribute('style', '-webkit-transform:' + s);


  document.getElementById("container").appendChild(d);
}
#container {
  position: relative;
  margin:100px auto; /* 80x + 20px */
  width:200px; /* 2*80px + 2*20px */
}

.box {
  background: #d0d0d0;
  width: 20px;
  height: 30px;
  border-radius: 7px;
  position: absolute;
  border: 1px solid black;
  /* the below conmbined with the translate(-50%,-50%) in the JS will center */
  top:50%;
  left:50%;
}

.box:hover {
  background: red;
}
<div id='container'></div>


推荐阅读