DIV盒子实现水平垂直居中的方法

目录 CSS2017年3月25日

记录下学习css的进程,记录一下遇到的难点。


绝对定位下DIV盒子的位置

  • 垂直水平都居中

方法一:

css样式

  1. .test1 {
  2.   position:fixed;
  3.   width:200px;
  4.   height:100px;
  5.   background-color:red;
  6.   left:50%;
  7.   top:50%;
  8.   margin-left:-100px;/*width宽度的一半*/
  9.   margin-top:-50px;/*height宽度的一半*/
  10. }

实现的效果:垂直水平都居中如下图css-center

方法2:

css样式:

  1. .test2 {
  2.   position:fixed;
  3.   width:200px;
  4.   height:100px;
  5.   background-color:red;
  6.   left:0;
  7.   right:0;
  8.   top:0;
  9.   bottom:0;
  10.   margin:auto auto;
  11. }

实现的效果:垂直水平都居中如下图css-center

  • 水平或垂直方向上的居中

以上两种方法第一种只设置水平的leftmargin-left属性即可实现水平居中,只设置topmargin-top属性即可实现垂直居中;第二种水平居中只需设置left:0right:0margin:0 auto即可实现,垂直居中只需设置top:0bottom:0margin:auto 0即可实现。

子DIV在父DIV中的居中

子DIV位置为默认值时的定位:即position:static,或者position:relative时

水平居中的子div css样式

  1. /*css样式*/
  2. .test1 {
  3.   position:fixed;
  4.   width:400px;
  5.   height:200px;
  6.   background-color:red;
  7.   left:50%;
  8.   top:50%;
  9.   margin-left:-200px;/*width宽度的一半*/
  10.   margin-top:-100px;/*height宽度的一半*/
  11.   text-align:center;
  12. }
  13. .test2 {
  14.   position:static;
  15.   width:200px;
  16.   height:100px;
  17.   background-color:burlywood;
  18.   border:1px solid #000;
  19.   text-align:right;
  20.   margin:0 auto;
  21. }
  22. /*html内容*/
  23. <div class="test1">我在中间<div class="test2">我在右边</div></div>

效果如下图所示,text-align规定了div中文本元素的对齐方式,子div只需设置外边距margin:0 auto就能实现水平居中,子div位置

子DIV位置为absolute时,即position:absolute,可以使用left、right、top、bottom相对于父DIV定位(父DIV位置必需是fixed、absolute、relative其中一种)

水平居中css

  1. .test1 {
  2.   position:relative;
  3.   width:400px;
  4.   height:200px;
  5.   background-color:red;
  6.   text-align:center;
  7. }
  8. .test2 {
  9.   position:absolute;
  10.   width:200px;
  11.   height:100px;
  12.   background-color:burlywood;
  13.   border:1px solid #000;
  14.   text-align:rightright;
  15.   left:0;
  16.   rightright:0;
  17.   margin:0 auto;
  18. }
  19. 或者
  20. .test2 {
  21.   position:absolute;
  22.   width:200px;
  23.   height:100px;
  24.   background-color:burlywood;
  25.   border:1px solid #000;
  26.   text-align:right;
  27.   left:50%;
  28.   margin-left:-100px;/*width宽度的一半*/
  29. }

实现的效果如下图子DIV位置

暂无评论

发表评论