css让一个div绝对居中
<!-- html页面 -->
<body>
<div>
</div>
</body>
方法1
/* css */
html,body{
height: 100%;
}
body{
margin: 0;
background-color: bisque;
position: relative;
}
div{
background-color: aqua;
width: 80px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -40px;
margin-top: -100px;
}
该方法利用css中父相子绝,让div根据body来进行定位(不加 position: relative;相对定位的话,默认也会相对body来进行定位). left: 50%; top: 50%;会使该div左上角在页面中间.加上 margin-left: -40px; margin-top: -100px;就形成了绝对居中. 该方法适用于宽高都确定的情况下
方法2
/* css */
html,
body {
height: 100%;
}
body {
margin: 0;
background-color: bisque;
position: relative;
}
div {
background-color: aqua;
width: 80px;
height: 200px;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
该方法是将元素完全脱离文档流使用margin: auto;将div上下,左右都完全居中;
方法3
/* css */
html,
body {
height: 100%;
}
body {
margin: 0;
background-color: bisque;
display: flex;
justify-content: center;
align-items: center;
}
div {
background-color: aqua;
width: 80px;
height: 200px;
}
该方法利用的css3的弹性盒子使横轴以及纵轴都达到了居中的效果 IE10及其以下版本都不兼容
方法4
/* css */
html,
body {
height: 100%;
}
body {
margin: 0;
background-color: bisque;
position: relative;
}
div {
background-color: aqua;
width: 80px;
height: 200px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
该方法利用的css3中 transform属性中translate(-50%, -50%)进行的一个2D的转换,达到了居中的效果
IE10及其以下版本都不兼容
方法5
/* css */
body {
margin: 0;
background-color: bisque;
width: 2000px;
height: 1000px;
display: table-cell;
text-align: center;
vertical-align: middle;
}
div {
background-color: aqua;
width: 80px;
height: 200px;
display: inline-block;
}
该方法利用文本居中,(不常用).而且必须要有绝对的宽和高百分比的宽高也不可以
方法6
// 基本样式的设定
// box代表div
box.style.width = '80px'
box.style.height = '200px'
box.style.background = ' aqua'
document.body.style.position = 'relative'
document.body.style.background = 'bisque'
let htm = document.documentElement
let htmWidth = htm.clientWidth
let htmHeight = htm.clientHeight
let boxW = box.clientWidth
let boxH = box.clientHeight
box.style.position = 'absolute'
box.style.left = (htmWidth-boxW)/2 +'px'
box.style.top =( htmHeight-boxH)/2 +'px'
该方法也是用的绝对定位,利用js算出left,和top的精确值,绝对定位到页面的中间