css怎么让div垂直居中


本文摘自PHP中文网,作者青灯夜游,侵删。

css让div垂直居中的方法:1、使用绝对定位和负外边距进行居中;2、利用伪元素和inline-block、vertical-align进行居中;3、利用table布局进行居中;4、使用固定定位和transform属性进行居中。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

我们都知道,固定高宽的div在网页中垂直居中很简单,相信大家也很容易的写出来,但是不是固定高宽的div如何垂直居中呢?我们在网页布局,特别是手机等web端网页经常是不固定高宽的div,那么这些div如何垂直居中呢?这篇文章,我总结一下。

固定高宽div垂直居中(使用绝对定位和负外边距)

1.gif

如上图,固定高宽的很简单,写法如下:

1

2

3

4

5

6

7

position: absolute;

left: 50%;

top: 50%;

width:200px;

height:100px;

margin-left:-100px;

margin-top:-50px;

不固定高宽div垂直居中的方法

方法一:伪元素和inline-block、vertical-align

用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。

html如下:

1

2

3

4

5

6

7

8

<div class="block" style="height: 300px;">

 

    <div class="centered">

        <h1>haorooms案例题目</h1>

        <p>haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容</p>

    </div>

 

</div>

css如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/* This parent can be any width and height */

.block {

  text-align: center;

}

 

/* The ghost, nudged to maintain perfect centering */

.block:before {

  content: '';

  display: inline-block;

  height: 100%;

  vertical-align: middle;

  margin-right: -0.25em; /* Adjusts for spacing */

}

 

/* The element to be centered, can

   also be of any width and height */

.centered {

  display: inline-block;

  vertical-align: middle;

  width: 50%;

}

方法二:用table布局

可以用table布局方法,但是这种方法也有局限性!

写法如下:

1

2

3

4

5

6

7

<table style="width: 100%;">

  <tr>

     <td style="text-align: center; vertical-align: middle;">

          Unknown stuff to be centered.

     </td>

  </tr>

</table>

由于table写法比较费时,你也可以用div代替table,写法如下:

html:

1

2

3

4

5

<div class="something-semantic">

   <div class="something-else-semantic">

       Unknown stuff to be centered.

   </div>

</div>

css:

阅读剩余部分

相关阅读 >>

最全的css样式整理总结

css margin-right属性怎么用

什么是css的行内式?

css选择第几个子元素用什么选择器

css中的animation是什么

css如何让a标签不可点击

css怎么更改超链接字体颜色

css文字颜色渐变的三种实现方式(附代码)

css text-indent属性怎么用

样式表css有哪几种类型

更多相关阅读请进入《css》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...