How to make div2 in the horizontal middle of div1
You can use js to dynamically calculate the width and height of the two and then divide by 2 to set The padding of div1
<style>div{margin:0;padding:0}#div1{position:relative;height:200px;width:200px;background-color:red}#div2{position:absolute;height:100px;width:100px;background-color:yellow;top:50%;margin-top:-50px;left:50%;margin-left:-50px}</style><div id="div1"> <div id="div2"> </div></div>
<style>div{margin:0;padding:0}#div1{position:relative;height:200px;width:200px;background-color:red}#div2{position:absolute;height:100px;width:100px;background-color:yellow;top:50%;margin-top:-50px;left:50%;margin-left:-50px}</style><div id="div1"> <div id="div2"> </div></div>
The extension is To extend, you can just remove the width attribute of div1
As long as the width of div2 is fixed.
<style>div{margin:0;padding:0}#div1{position:relative;height:200px;width:200px;background-color:red}#div2{position:absolute;height:100px;width:100px;background-color:yellow;top:50%;margin-top:-50px;left:50%;margin-left:-50px}</style><div id="div1"> <div id="div2"> </div></div>