下面是CSS实现子元素div水平垂直居中的攻略,包含两个示例。
下面是CSS实现子元素div水平垂直居中的攻略,包含两个示例。
一、通过flex布局实现
- HTML代码
<div class="container">
<div class="child"></div>
</div>
- CSS代码
.container {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
border: 1px solid black;
}
.child {
width: 100px;
height: 100px;
background-color: red;
}
上述代码中,.container类设置了display: flex,justify-content: center和align-items: center这三个属性。这使得.container元素内的子元素在水平和垂直方向上都居中对齐。另外,我们还定义了一个高度值用于展示居中效果。
二、通过百分比和transform属性实现
- HTML代码
<div class="container">
<div class="child"></div>
</div>
- CSS代码
.container {
position: relative;
width: 300px;
height: 300px;
background-color: gray;
}
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: red;
}
上述代码中,.container类设为position: relative,是为了让其内部设定的子元素.child使用position: absolute属性时,相对于.container元素的位置进行定位。
.child元素的left属性设为50%,表示在水平方向上占据.container宽度的50%的位置。然后通过使用transform软件,把元素向左移动自身宽度一半的长度。同时,同样的方式设置.top,把元素向上移动自身高度一半的长度。这样一来,.child元素就实现了在水平和垂直方向上居中对齐。
本文标题为:CSS实现子元素div水平垂直居中的示例
基础教程推荐
- 用html代码给网页加个live2d看板娘吧 2023-10-26
- vue等框架对Tabs、Moda等设置固定高度后没有滚动条问题 2023-07-09
- javascript报错:xxx.foreach is not a function 2022-07-25
- AJAX跨域问题解决方案详解 2023-02-23
- HTML中的超链接 2023-10-26
- Ajax提交Form表单页面仍会刷新问题的快速解决办法 2023-01-26
- 「免费开源」基于Vue和Quasar的前端SPA项目crudapi后台管理系统实战之docker部署(八) 2023-10-08
- JS中的async与await怎么使用 2023-08-08
- 探讨Ajax中有关readyState(状态值)和status(状态码)的问题 2023-01-20
- web中自定义鼠标样式将其显示为左右箭头 2023-12-08
