Web前端基础知识(四)——垂直居中的四种方式

设置上下padding相等实现居中

这种设置简单粗暴
代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
   <style>
     .ct{
   padding: 50px 0px;
   text-align: center;
   background: #eee;
 }
   </style>
 </head>
 <body>
   <div class="ct">
     <p>padding设置居中</p>
     <p>padding设置居中</p>
   </div>
 </body>
 </html>

效果:
这里写图片描述

绝对定位实现居中

绝对定位的设置适用于弹窗一类,但是会脱离文档流。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
  html,body {
  height: 100%;
}
.dialog {
  position: absolute;
  left: 50%;
  top: 50%; 
  margin-left: -200px;
  margin-top: -150px;
  width: 400px;
  height: 300px;
  box-shadow: 0px 0px 3px #000;
}
.dialog .header{
  padding: 10px;
  background: #000;
  color: #fff;
}
.dialog .content{
  padding: 10px;
}
  </style>
</head>
<body>
  <div class="dialog">
    <div class="header">我是标题</div>
    <div class="content">我是内容</div>
  </div>
</body>
</html>

效果:
这里写图片描述

vertical-align实现居中

vertical-align作用在行内元素和表格上。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
  .box{
  width: 300px;
  height: 500px;
  border: 1px solid ;
  text-align: center;
}

.box:before{
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}
.box img{
  vertical-align: middle;

}
  </style>
</head>
<body>
  <div class="box">
    <img src="http://img.hb.aicdn.com/844cc8626177f5429032aae7e5f42d0aa05b57a23437-8MCz1J_fw658" alt="">
  </div>

</body>
</html>

效果:
这里写图片描述

使用table-cell实现居中

    display:table-cell属性指让标签元素以表格单元格的形式呈现,类似于td标签。目前IE8+以及其他现代浏览器都是支持此属性的,但是IE6/7不支持,这一事实也是大大制约了display:table-cell属性在实际项目中的应用。
    table-cell同样会被其他一些CSS属性破坏,例如float, position:absolute,所以,在使用display:table-cell与float:left或是position:absolute属性尽量不用同用。设置了display:table-cell的元素对宽度高度敏感,对margin值无反应,响应padding属性,基本上就是活脱脱的一个td标签元素了。

引用来源

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>

  .box{

  width: 500px;
  height: 500px;
  border: 1px solid ;
  display: table-cell; 
  vertical-align: middle;
  text-align: center;
  }

  </style>
</head>
<body>
  <div class="box">
    <img src="http://img.hb.aicdn.com/844cc8626177f5429032aae7e5f42d0aa05b57a23437-8MCz1J_fw658" alt="">
  </div>

</body>
</html>

效果:
这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值