讓DIV垂直居中+水平居中+圓角屬性
阿新 • • 發佈:2019-01-08
讓既垂直有水平居中首先就要知道div的寬度和高度,然後設定他的position屬性定位,再設定它從頂部到父元素和左邊到父元素的距離都為50%,然後再設定它的外邊距margin上邊自己高度的一半,左邊為自己寬度的一半,如下css程式碼。
html:
<div class="main">
<div class="content"></div>
</div>
css:
.main { width: 600px; height: 400px; border: 1px solid; background: #EFEFEF; text-align: center; } .content{ background: #A72525; height: 250px; width: 250px; position: relative; left: 50%; top: 50%; border-radius: 50%;//圓角 margin: -125px 0 0 -125px; }
然後設定圓角屬性為50%就變成一個遠居中了。
js實現居中螢幕中間:
//獲取滾動條 function getScroll() { return{ top : document.documentElement.scrollTop || document.body.scrollTop, left : document.documentElement.scrollLeft || document.body.scrollLeft } }; //獲取div大小 function getInner() { if (typeof window.innerWidth != 'undefined') { return { width : window.innerWidth, height : window.innerHeight } } else { return { width : document.documentElement.clientWidth, height : document.documentElement.clientHeight } } } var box = document.getElementsByClassName('main'); var top = (getInner().height - 400) / 2 + getScroll().top; // 400是div的高度 var left = (getInner().width - 600) / 2 + getScroll().left; //600是div的寬度 box[0].style.top = top + 'px'; box[0].style.left = left + 'px';
然後就可以了。