css水平居中和垂直居中_html/css_WEB-ITnose

php中文网
发布: 2016-06-24 11:58:26
原创
1246人浏览过

水平居中:
内联元素:text-align:center;相对于父级居中显示
块级元素:margin:0 auto;但是需要同时width,否则无法看到效果
多个块级元素居中:在此想要探讨一下display:inline-block;和display:flex;
方法1:在父级上设置text-align:center;在元素上设置:display:inline-block;同时为了使文字向左显示,设置了text-align:left;在浏览器中的显示为,子元素高度自适应,底部对齐。
方法2:在子元素上设置display:center;justify-content:center;子元素的高度一致,与元素中内容最多的高度相同。
二种方法在谷歌,火狐,360均兼容,但是第2种方法在ie10中不兼容,之前的ie版本可想也是不兼容的。当然在此也要处理由于浮动导致离层,父级背景颜色加不上去的问题。

 1 <main class="inline-block-center"> 2   <div> 3     I'm an element that is block-like with my siblings and we're centered in a row. 4   </div> 5   <div> 6     I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do. 7   </div> 8   <div> 9     I'm an element that is block-like with my siblings and we're centered in a row.10   </div>11 </main>
登录后复制

 

 1 <main class="flex-center"> 2   <div> 3     I'm an element that is block-like with my siblings and we're centered in a row. 4   </div> 5   <div> 6     I'm an element that is block-like with my siblings and we're centered in a row. I have more content in me than my siblings do. 7   </div> 8   <div> 9     I'm an element that is block-like with my siblings and we're centered in a row.10   </div>11 </main>
登录后复制

 

 1 body { 2   background: #f06d06; 3   font-size: 80%; 4 } 5 main { 6   background: white; 7   margin: 20px 0; 8   padding: 10px; 9 }10 main div {11   background: black;12   color: white;13   padding: 15px;14   max-width: 125px;15   margin: 5px;16 }17 .inline-block-center {18   text-align: center;19 }20 .inline-block-center div {21   display: inline-block;22   text-align: left;23 }24 .flex-center {25   display: flex;26   justify-content: center;27 }
登录后复制

垂直居中:

居然设计家
居然设计家

居然之家和阿里巴巴共同打造的家居家装AI设计平台

居然设计家 64
查看详情 居然设计家

方法1:设置padding-top和padding-bottom的值相等
方法2:设置height和line-height的值相等
方法3:固定高度可以有一种处理方式position:absolute;top:50%;height:100px;margin-top:-50px;如果高度不固定,也可以使用js动态获取高度来。
还有css3的一些属性,考虑到兼容性问题不在叙述。

立即学习前端免费学习笔记(深入)”;

相关标签:
css
HTML速学教程(入门课程)
HTML速学教程(入门课程)

HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号