摘要:本篇教程探讨了如何实现水平垂直居中,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。
本篇教程探讨了如何实现水平垂直居中,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 。
水平居中:
· 行内元素
只需要把行内元素包裹在一个属性display为block的父层元素中,并且把父层元素添加属性text-align:center;
· 块级元素
设置width值并添加属性margin:0 auto;
o 多个块级元素
将元素的display属性设置为inline-block,并且把父元素的text-align属性设置为center
o 多个块级元素(flex布局)
给父级元素添加属性:display:flex;和justify-content:center;
垂直居中:
· 行内元素(单行)
将元素的height和line-height设置的和父元素一样高度即可实现垂直居中
· 行内元素(多行)
在父元素中设置display:table-cell;vertical-align:center;
· 块级元素(已知高度)id值为”div“
#div{
top: 50%;
margin-top: -50px; /* margin-top值为自身高度的一半 */
position: absolute;
padding:0;
}
水平垂直居中
· 已知宽高 方案1
<div id="div1">
<p>水平垂直居中</p></div>
<style>
#div1{
width:200px;
height: 200px;
position: absolute;
left:50%;
top:50%;
margin-top: -100px;
margin-left: -100px;
background-color: antiquewhite;
text-align: center;
}</style>
· 已知宽高 方案2
<div id="div1">
<p>水平垂直居中</p></div>
<style>
#div1{
width:200px;
height: 200px;
position: absolute;
margin: auto;
left:0;
right:0;
top:0;
bottom:0;
text-align: center;
background-color: antiquewhite;
}
</style>
· 未知宽高(css3的transform)
<div id="div1">
<p>水平垂直居中</p></div>
<style>
#div1{
position: absolute;
left: 50%;
top:50%;
transform: translate(-50%,-50%);//使用css3的transform属性
}
</style>
· 未知宽高(flex布局)
<div id="div1">
<p>水平垂直居中</p></div>
<style>
#div1{
display: flex; //使用flex布局
justify-content: center; //子元素水平居中
align-items: center; //子元素垂直居中
height: 400px; //设置高度来查看垂直居中效果
background-color: antiquewhite;
}
</style>
本文由职坐标整理发布,学习更多的HTML5/CSS3相关知识,请关注职坐标WEB前端HTML5/CSS3频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号