法一:margin负值调整(确定容器的宽和高)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
<style>
div{
position:absolute;
width:500px;
height:300px;
top:50%;
left:50%;
background-color:pink;
margin: -150px 0 0 -250px;
}
</style>
<body>
<div>liao</div>
</body>
</html>思路就是既然已经有了元素宽度和高度,那么先绝对定位把左顶点放到中心,但我们最后的目标是把图形中点放到中心,在已有宽度高度情况下通过margin负值产生位移调整中点就行了
ps:margin负值真的是比较复杂,可参考大佬文章
https://www.cnblogs.com/fbzs/p/6373315.html
https://www.cnblogs.com/xiaohuochai/p/5314289.html
法二:css3属性
同样原理不解释,上代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
<style>
div{
position: absolute; /* 相对定位或绝对定位均可 */
width:500px;
height:300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: pink; /* 方便看效果 */
}
</style>
<body>
<div>liao</div>
</body>
</html>法三、flex布局
这个可能是本人flex学艺不精吧 在写这个博文的时候反正感觉
align-items: center和justify-content: center并未起效orz
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Bliao</title>
</head>
<style>
.container {
display: flex;
min-height: 100vh;
margin: 0;
}
#neirong{
//align-items: center;
//justify-content: center;
width: 12em;
height: 8em;
margin: auto;
background-color: pink;
}
</style>
<body>
<div class="container">
<div id="neirong"></div>
</div>
</body>
</html>
381

被折叠的 条评论
为什么被折叠?



