CSS水平、垂直居中,吃透这份阿里P8纯手打前端面经,带你搞懂前端启动速度优化

.parent{

position: relative;

height: 100px;

background: red;

}

.child{

position: absolute;

left: 50%;

/或者使用margin-left: -宽/2/

transform: translateX(-50%);

background: blue;

}

效果:

在这里插入图片描述

垂直居中

1. 行内元素

line-height:高度

2. 块级元素高度一定

  • 定位实现

.parent{

position: relative;

background: #008a00;

height: 200px;

}

.child{

position: absolute;

top: 50%;

height: 100px;

margin-top: -50px; /高的一半/

background: yellow;

}

  • 绝对定位+margin: 0

.parent{

position: relative;

background-color: purple;

width: 150px;

height: 150px;

}

.child{

position: absolute;

margin: auto;

top: 0;

bottom: 0;

width: 50px;

height: 50px;

background-color: #f0ad4e;

}

在这里插入图片描述

3. 高度不确定

  • 定位实现

.parent{

position: relative;

background: #008a00;

height: 200px;

}

.child{

position: absolute;

top: 50%;

transform: translateY(-50%);

background: yellow;

}

效果:

在这里插入图片描述

  • flex布局

.parent{

display: flex;

background: #008a00;

height: 200px;

align-items: center;

}

.child{

background: yellow;

}

效果:

在这里插入图片描述

  • 使用grid布局.

下面方法是给父元素设置align-items: center或者align-content: center;

还有办法是给子元素设置align-self: center;

.parent{

display: grid;

border: red 1px solid;

width: 280px;

height: 200px;

align-items: center;

}

.child{

background-color: #afd9ee;

font-size: 40px;

}

在这里插入图片描述

  • table布局

表格布局vertical-align: middle;

.parent{

display: table;

background: #008a00;

height: 200px;

}

.child{

display: table-cell;

vertical-align: middle;

background: yellow;

}

效果:

在这里插入图片描述

水平垂直居中

1.position元素已知宽度

父元素:position: relative;

子元素:position: absolute;

marginmargin-top设置为-高度的一半

margin-left设置为-宽度的一半

.box {

height: 500px;

小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级前端工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!
因此收集整理了一份《2024年Web前端开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频

如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注:前端)
img

读者福利

========

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

由于篇幅过长,就不展示所有面试题了,想要完整面试题目的朋友(另有小编自己整理的2024大厂高频面试题及答案附赠)


-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3NpbmF0XzM3OTAzNDY4,size_16,color_FFFFFF,t_70)

  • 18
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值