元素居中的方式
1.单行文本水平居中
说明:
只针对块元素中的行内元素,或者 行内块元素,使用text-align:center;
属性
HTML:
<div class="box">
<span>
我是文字
</span>
</div>
CSS:
.box {
background-color: pink;
height: 200px;
width: 200px;
text-align: center;
}
图示:
2.单行文本水平垂直居中
说明:
使块元素中的行内元素水平垂直居中
垂直居中:line-height:
取值盒父元素高度一样
CSS:
.box {
background-color: pink;
height: 200px;
width: 200px;
text-align: center;
line-height: 200px;
}
3.块元素水平居中
说明:
水平居中:块元素有固定宽度(宽度不为100%)
margin:0 auto;
HTML:
<div class="box">
<div class="box2"></div>
</div>
CSS:
.box {
background-color: pink;
height: 200px;
width: 200px;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
margin: 0 auto;
}
图示:
4.块元素垂直居中
1.定位(position)
CSS:
.box {
background-color: pink;
height: 300px;
width: 300px;
/*相对定位*/
position: relative;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
/*绝对定位*/
position: absolute;
/*垂直方向 向下移动相对于父盒子的25%*/
top: 50%;
/*水平方向 向右移动相对于父盒子的25%*/
left: 50%;
margin-left: -50px;
margin-top: -50px;
}
图示:
2.弹性盒子(display:flex)
CSS:
.box {
background-color: pink;
height: 200px;
width: 200px;
/* 设置为弹性盒子 */
display: flex;
}
.box2 {
width: 100px;
height: 100px;
background-color: yellow;
/* 只有一个元素时,使用margin:auto */
margin: auto;
}
图示:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端