登录  /  注册

css怎么设置居中对齐

藏色散人
发布: 2021-04-29 09:07:33
原创
5596人浏览过

css设置居中对齐的方法:1、通过“text-align:center”或“margin:垂直 auto;”实现水平居中;2、通过“line-height”实现垂直居中;3、通过“弹性布局”实现水平垂直居中等等。

css怎么设置居中对齐

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

css——居中对齐方法

  • text-align:center —— 水平居中

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

  • margin:垂直 auto; —— 水平居中

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

 .father{
           width:500px;
           height:200px;
           background-color::#f98769;
           overflow:hidden;//不可缺少否则margin-top不生效       }
        .son{
            width: 100px;
            height: 100px;
            margin:50px auto ;
            background-color: #ff0000;
        }
登录后复制
  • line-height —— 垂直居中

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

  • 使用表格 —— 水平、垂直居中

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

  • 弹性布局 —— 水平、垂直居中
.father{display:flex;justity-content:center;align-items:center;}.father{display:flex;flex-direction:column;//改变主轴为cross axisjustity-content:center;}
登录后复制
  • 使用display:table-cell —— 水平、垂直居中

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

.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 }
登录后复制
  • 奇淫技巧——子绝父相(已知子元素宽高) —— 水平、垂直居中

.father{position:relative;}.son{//m、n为子盒子宽、高的一半position:absolute;left:50%;top:50%;margin-left:-mpx;margin-top:-npx;
登录后复制
  • 未知子元素宽高 —— 水平、垂直居中

.father {
    position:relative;}.son {
    position:absolute;
    top:50%;
    left:50%:
    transform:translate(-50%,-50%) /*单独设置transform:translateY(-50%);*/}
登录后复制
  • 伪元素法 —— 垂直居中

		 .father{
            position: relative;
        }
        .father::before{
            content: " ";
            display: inline-block;
            height: 100%;
            width: 1%;
            vertical-align: middle;
        }
        .son{
            display: inline-block;
            vertical-align: middle;
        }
登录后复制

更多详细的HTML/css知识,请访问css视频教程栏目!

以上就是css怎么设置居中对齐的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

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