css居中对齐怎么设置


本文摘自PHP中文网,作者coldplay.xixi,侵删。

css居中对齐的设置方法:1、水平居中【text-align:center】;2、水平居中【margin:0 auto】;3、垂直居中【line-height】;4、使用表格,水平、垂直居中;5、弹性布局,水平、垂直居中。

本教程操作环境:windows7系统、css3版,DELL G3电脑。

css居中对齐的设置方法:

1、text-align:center ―― 水平居中

仅对文字、图片、按钮等行内元素有效(display设置为inline或inline-block等)进行水平居中

2、margin:0 auto; ―― 水平居中

仅水平居中,且对浮动元素定位无效

1

2

3

4

5

6

7

8

9

10

11

12

.father{

          width:500px;

          height:200px;

          background-color::#f98769;

          overflow:hidden;//不可缺少否则margin-top不生效

      }

       .son{

           width: 100px;

           height: 100px;

           margin:50px auto ;

           background-color: #ff0000;

       }

3、line-height ―― 垂直居中

line-height=height ,仅对一行文字有效

4、使用表格 ―― 水平、垂直居中

对td/th的align=‘center’和valign=‘middle’两属性可以水平和垂直居中

5、弹性布局 ―― 水平、垂直居中

1

2

3

4

5

6

7

8

9

10

.father{

display:flex;

justity-content:center;

align-items:center;

}

.father{

display:flex;

flex-direction:column;//改变主轴为cross axis

justity-content:center;

}

6、使用display:table-cell ―― 水平、垂直居中

对于那些不是表格的元素,我们可以通过display:table-cell 来把它模拟成一个表格单元格

1

2

3

4

5

6

7

8

9

10

.father{

    height:300px;

    background:#ccc;

    display:table-cell; /*IE8以上及Chrome、Firefox*/

    vertical-align:middle; /*IE8以上及Chrome、Firefox*/

    text-align:center;

 }

 .son{

 display:inline-block;//或是inline

 }

7、奇淫技巧――子绝父相(已知子元素宽高) ―― 水平、垂直居中

1

2

3

4

5

6

7

8

9

.father{

position:relative;

}

.son{//m、n为子盒子宽、高的一半

position:absolute;

left:50%;

top:50%;

margin-left:-mpx;

margin-top:-npx;

8、未知子元素宽高 ―― 水平、垂直居中

1

2

3

4

5

6

7

8

9

.father {

    position:relative;

}

.son {

    position:absolute;

    top:50%;

    left:50%:

    transform:translate(-50%,-50%) /*单独设置transform:translateY(-50%);*/

}

9、伪元素法 ―― 垂直居中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

.father{

    position: relative;

}

.father::before{

    content: " ";

    display: inline-block;

    height: 100%;

    width: 1%;

    vertical-align: middle;

}

.son{

    display: inline-block;

    vertical-align: middle;

}

相关教程推荐:CSS视频教程

以上就是css居中对齐怎么设置的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

css怎么去掉斜体样式

css文字如何垂直居中

css如何设置背景

如何定义项目列表css

css怎么实现隐藏并占位

css怎么改字位置

css中怎么给按钮添加背景图片(详解及实例)

css如何使用:indeterminate选择器

css modules是什么

css外链式和导入式的区别是什么

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




打赏

取消

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

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

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

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

评论

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