实现页面(元素)居中(水平 垂直居中)的效果有很多种 我这里列举了几种
最终的效果图都是:图标就是我们元素
1.使用定位 在下面案例中 核心代码就是 :(这种是已经知道元素的(此处的元素就是img)宽高)
position: absolute;
top:50%;
left: 50%;
margin-left: -50px;//用来减去img宽度的一半
margin-top: -50px;//用来减去img高度的一半
style type="text/css">
.big{
width: 200px;
height: 240px;
border: 1px solid #ccc;
border-radius: 5px;
position: relative;
}
img{
width: 94px;
height: 94px;
position: absolute;
top:50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
</head>
<body>
<div class="big">
<img src="icon-tag001.png" alt="" class="img1">
</div>
2.还是使用定位 这里和第一种方法不同的是此处使用了margin:auto
(如果单独的使用是没有效果的 要和定位搭配使用)
img{
width: 94px;
height: 94px;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
3.用定位和transform搭配使用 与上两种不同的是 这个对于兼容性不太好但是优点是在不知道元素的宽高下也可以使用
margin: auto;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
4.使用弹性盒子 给父级设
display: flex;
align-items: center;/定义在交叉轴上对齐 水平居中/
justify-content: center;/定义在主轴上的对齐 垂直居中/
.big{
width: 200px;
height: 240px;
border: 1px solid #ccc;
border-radius: 5px;
/*position: relative;*/
display: flex;
align-items: center;/*定义在交叉轴上对齐 水平居中*/
justify-content: center;/*定义在主轴上的对齐 垂直居中*/
}
img{
width: 94px;
height: 94px;
}
5.将定位和calc()方法同时使用 注意方法内50% 减去 元素宽高时减号左右两边要空格
.big{
width: 200px;
height: 240px;
border: 1px solid #ccc;
border-radius: 5px;
position: relative;
}
img{
width: 94px;
height: 94px;
position: absolute;
top:calc(50% - 47px);
left:calc(50% - 47px);
}