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

设置上下padding相等实现居中

这种设置简单粗暴
代码:





JS Bin
   
 
 
   

padding设置居中

padding设置居中

效果:
Web前端基础知识(四)——垂直居中的四种方式_第1张图片

绝对定位实现居中

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


<html>
<head>
  <meta charset="utf-8">
  <title>JS Bintitle>
  <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>

效果:
Web前端基础知识(四)——垂直居中的四种方式_第2张图片

vertical-align实现居中

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


<html>
<head>
  <meta charset="utf-8">
  <title>JS Bintitle>
  <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>

效果:
Web前端基础知识(四)——垂直居中的四种方式_第3张图片

使用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标签元素了。

引用来源


<html>
<head>
  <meta charset="utf-8">
  <title>JS Bintitle>
  <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>

效果:
Web前端基础知识(四)——垂直居中的四种方式_第4张图片

你可能感兴趣的:(web前端)