简体   繁体   中英

How do I make my absolute-positioned elements responsive?

I am trying to center (horizontally & vertically) this circle of shapes in the middle of the container and make it responsive. I do not know how to keep the circular shape without absolute positioning. Any help is appreciated!

 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/

position them relatively to the container and then center the container:

 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>

Try using border-radius of 50%, relative positioning rather than absolute, and margin: auto. This will force the box to the center of its container.

.box {
    background: #d0d0d0;
    width: 20px;
    height: 30px;
    border-radius: 7px;
    position: relative;
    border: 1px solid black;
    margin: auto;
}

This css will create an ellipse rather than a circle, due to the different height and width attributes. If a circle is the behavior you were looking for, change heigh and width to have the same value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM