div盒子水平垂直居中的几种方法

      发布在:前端技术      评论:0 条评论

一、盒子没有固定的宽和高

方案1、使用transforms属性的translate平移

这是最简单的方法,不仅能实现绝对居中同样的效果,也支持联合可变高度方式使用。 

<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {
padding: 20px;
background: orange;
color: #fff;
position: absolute;
top: 50%;
left: 50%;
border-radius: 5px;
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

</style>
</head>
<body>
<div class="content">
我不知道我的高度和宽度是多少。
</div>
</body>
</html>

使用top:50%; left:50%;时,是以盒子的左上角为原点定位,是左上角的原点居中,但是元素本身并不居中。

transform:translate(-50%,-50%):分别向左向上移动自身长宽的50%,使其位于中心。

二、盒子有固定的宽和高


方案1、margin 负间距


1.必需知道该div的宽度和高度,


2.然后设置位置为绝对位置,


3.距离页面窗口左边框和上边框的距离设置为50%,这个50%就是指盒子左上角顶点距离页面左、上边界的50%,


4.最后将该div分别左移和上移,使整个盒子居中,左移和上移的大小就是该DIV(包括border和padding)宽度和高度的一半。

<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {

position: absolute;
width: 200px;
height: 200px;
border: 2px solid red;
background-color: yellow;
left:50%;
top:50%;
margin-left:-102px;
margin-top:-102px;
}

</style>
</head>
<body>
<div class="content">
我有固定的宽度和高度。
</div>
</body>
</html>

方案2、margin:auto实现绝对定位元素的居中(该方法兼容ie8以上浏览器)

此方案代码关键点:

1、上下左右均0位置定位;

 2、margin: auto;

<!DOCTYPE html>
<html>
<head>
<title>my-test</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.content {

position: absolute;
width: 200px;
height: 200px;
border: 2px solid red;
background-color: yellow;

left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}

</style>
</head>
<body>
<div class="content">
我有固定的宽度和高度。
</div>
</body>
</html>

原文链接:https://blog.csdn.net/qq_34200964/article/details/81711989


相关文章
热门推荐