实现行内元素实现水平和垂直居中的方式:
text-align: center;
line-height: Xpx;
实现元素的水平和垂直居中的几种方式:
1、使用弹性盒模型 实现水平和垂直居中。
display: flex;
justify-content: center;
align-items: center;
2、采取绝对定位配合margin的方式实现。(得设置固定的宽度和高度。)
position: absolute;
left: 50%;
top: 50%;
margin-left: -Xpx;
margin-top: -Xpx;
3、采取借助css3的变形属性Transform来完成。
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
4、盒子有宽高,但是不需要去计算偏移盒子的宽高。
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
这四种方法都能达到元素的水平垂直居中。
小练习:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./demo3.css">
</head>
<body>
<div class="box">
<div class="top">
<div class="tb"></div>
<div class="tl">
<img src="./imgs/baisei.png">
<div class="tlr">
<p>西贝莜面村代金卷</p>
<p>有效期:2016-03-31</p>
</div>
</div>
<div class="tr">
待使用
</div>
</div>
<div class="bottom">
<span>劵号</span>
<span>5436 4245 72</span>
<div class="cl"></div>
<div class="cr"></div>
<div class="bb"></div>
</div>
</div>
</body>
</html>
css:
*{margin: 0;padding: 0;list-style: none;}
html{
font-size: 10px;
}
img{
display: block;
}
.box{
height: 17.9rem;
display: flex;
flex-direction: column;
position: relative;
background: #F0F0F0;
}
.box .top{
margin: 10px ;
margin-bottom: 0;
padding-top: 10px;
display: flex;
justify-content: space-between;
background: white;
}
.box .top .tl{
padding-top: 1rem;
padding-left: 1rem;
padding-bottom: 1.5rem;
display: flex;
}
.box .top .tl img{
width: 4rem;
height: 4rem;
border-radius: 50%;
}
.box .top .tl .tlr{
padding-top: .5rem;
margin-left: .5rem;
}
.box .top .tl .tlr p:nth-of-type(2){
color: #ccc;
}
.box .top .tr{
text-align: center;
margin-right: 1rem;
margin-top: 1.5rem;
width: 6rem;
height: 1.8rem;
line-height: 1.8rem;
background: #EA0314;
color: white;
}
.box .bottom{
height: 1rem;
padding: 1.5rem;
margin: 10px ;
margin-top: 0;
border-top: 1px solid #ccc;
background: white;
position: relative;
}
.box .bottom .cl{
height: 1rem;
width: 1rem;
position: absolute;
top: -0.5rem;
left: -0.5rem;
background: #F0F0F0;
border-radius: 50%;
}
.box .bottom .cr{
height: 1rem;
width: 1rem;
position: absolute;
top: -0.5rem;
right: -0.5rem;
background: #F0F0F0;
border-radius: 50%;
}
.box .bottom span:nth-of-type(2){
color: #EA0314;
}
.box .tb{
width: 100%;
height: 1.6rem;
position: absolute;
top: 0;
background: url(../imgs/border.png) repeat-x;
}
.box .bb{
width: 100%;
height: 1.6rem;
position: absolute;
left: 0;
bottom: -1.2rem;
background: url(../imgs/border.png) repeat-x;
}
总结:望各位大佬指正。