水平垂直居中的实现
方法一:在已知宽度的情况下,对div改变外边距进行偏移达到效果。
.container {
width: 500px;
height: 500px;
background-color: orange;
position: relative;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
margin: -50px 0 0 -50px;
}
方法二:宽度未知的情况,使用tansform属性。
.container {
width: 500px;
height: 500px;
background-color: orange;
position: relative;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
方法三:使用弹性布局flex。
.container {
display: flex;
justify-content: center;
align-items: center;
width: 500px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
}
方法四:使用table-cell,需要注意的是content块需要给予inline-block。
.container {
display: table-cell;
/* 垂直居中 */
vertical-align: middle;
/* 水平居中 */
text-align: center;
width: 500px;
height: 500px;
background-color: orange;
}
.content {
display: inline-block;
width: 100px;
height: 100px;
background-color: red;
}
方法五:使用grid布局
.container {
display: grid;
width: 500px;
height: 500px;
background-color: orange;
margin: 0 auto;
}
.content {
width: 100px;
height: 100px;
background-color: red;
justify-self: center;
align-self: center;
}
还有更多,等你探索...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通