温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

好程序员前端教程css对齐方案总结

发布时间:2020-08-09 23:15:09 阅读:157 作者:好程序员 栏目:移动开发
前端开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

好程序员前端教程css对齐方案总结
垂直居中
通用布局方式(内敛元素和块状元素都适用)

利用flex:
核心代码:

.container{
    display:flex;
     flex-direction:column;
     justify:center
}

利用transformX(-50%):
核心代码:

.container{
            width300px;
            height300px;
            background: red;
            position:relative;
        	}
.child{
            position: absolute;
            top50%;
            transformtranslateY(-50%);
            -webkit-transformtranslateY(-50%);
 			}

内敛元素的垂直居中

单行内敛元素:设置内敛元素的高度和行高相等
核心代码:

.container {
    height120px;
    line-height120px;
}

块状元素

固定元素高度的块状元素
核心代码

.container{
    position: relative;
}
.child{
    position: absolute;
      top50%;
      height100px;
      margin-top: -50px; 
}

未知高度的块状元素
当垂直居中的元素的高度和宽度未知时,我们可以借助CSS3中的transform属性向Y轴反向偏移50%的方法实现垂直居中。但是部分浏览器存在兼容性的问题。
核心代码:

.container {
    position: relative;
}
.child {
    position: absolute;
    top50%;
    transformtranslateY(-50%);
}

水平居中
通用布局方式

flex布局
核心代码:

.container{
display: flex;  
              justify-content: center;
}
absoulte+transform

核心代码:

.container{
position:relative;
}
.child{
  position: absolute;
                left50%;
                transformtranslateX(-50%);
}

内敛元素水平居中

text-align:center
核心代码:

.container{
text-align:center
}

块状元素水平居中

使用 margin:0 auto 必须注明子元素和父元素的宽度
核心代码:

.container{
margin:0 auto
}

多块状元素:
利用内敛元素布局方式container属性为text-align:center;
核心代码:

.container{
text-align: center;
}
.child{
display: inline-block;
}

水平垂直居中
固定宽高元素水平垂直居中

通过margin平移元素整体宽度的一半,使元素水平垂直居中。
核心代码:

.container {
    position: relative;
}
.child {
    width300px;
    height100px;
    padding20px;
    position: absolute;
    top50%;
    left50%;
    margin: -70px 0 0 -170px;
}

未知宽高元素水平垂直居中

利用2D变换,在水平和垂直两个方向都向反向平移宽高的一半,从而使元素水平垂直居中。
核心代码:

.parent {
    position: relative;
}
.child {
    position: absolute;
    top50%;
    left50%;
    transformtranslate(-50%, -50%);
}

利用flex布局
利用flex布局,其中justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;而align-items属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。
核心代码:

.container {
    display: flex;
    justify-content: center;
    align-items: center;
}

相对于 body 的水平垂直居中

列表布局(兼容性好)
核心代码:

.outer {
    display: table;
    position: absolute;
    height100%;
    width100%;
}
.middle {
    display: table-cell;
    vertical-align: middle;
}
.inner {
    margin-left: auto;
    margin-right: auto; 
    width400px;
}

position 布局
核心代码

.container{
	position: absolute;
	margin: auto;
	left0;
	top0;
	right0;
	bottom0;
	}

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:http://blog.itpub.net/69913864/viewspace-2639086/

AI

开发者交流群×