想要通过position定位实现div底端对齐,需要以下步骤:
想要通过position定位实现div底端对齐,需要以下步骤:
- 给父元素设置 position: relative;
这一步是为了使子元素能够参照自己正确的定位。
- 给子元素设置 position: absolute; bottom: 0;
这一步是为了让子元素的底部与父元素的底部对齐,并且 bottom 属性的值为 0 表示将子元素定位在父元素底部。
下面是两个示例:
示例一:
HTML 代码:
<div class="parent">
<div class="child">
这是一段文本
</div>
</div>
CSS 代码:
.parent {
width: 200px;
height: 300px;
background-color: #ccc;
position: relative;
}
.child {
position: absolute;
bottom: 0;
width: 100%;
height: 50px;
background-color: #f00;
color: #fff;
text-align: center;
}
解释:通过给 .parent 设置 position: relative;,使得 .child 能够参照 .parent 定位。给 .child 设置 position: absolute; bottom: 0;,使得 .child 的底部与 .parent 的底部对齐。同时 .child 的 width 设置为 100%,使其与 .parent 的宽度相等;height 设置为 50px,这样子元素就有了高度,才能实现子元素底部对齐。
示例二:
HTML 代码:
<div class="parent">
<div class="child">
<img src="image.jpg" alt="这是一张图片">
</div>
</div>
CSS 代码:
.parent {
width: 300px;
height: 200px;
background-color: #ccc;
position: relative;
}
.child {
position: absolute;
bottom: 0;
text-align: center;
}
img {
height: 100%;
max-width: none;
display: inline-block;
vertical-align: bottom;
}
解释:同样通过给 .parent 设置 position: relative; 以及给 .child 设置 position: absolute; bottom: 0; 实现子元素底部对齐。这个示例也同时涉及到如何使图片在子元素内垂直居中的问题。首先要确保 .child 的 width 等于 .parent 的 width,然后设置 img 的 height 为100%,这样图片的高度就等于 .child 的高度,再通过 display: inline-block; 和 vertical-align: bottom; 属性,实现图片在 .child 的内部垂直居中。max-width: none; 则是为了避免图片在等比缩放时宽度不够而出现的问题。
本文标题为:通过position定位实现div底端对齐


- ajax和fetch的区别点总结 2023-02-24
- ElementUI table无缝循环滚动的示例代码 2022-10-22
- 关于ajax的使用方法_例题、ajax的数据处理 2023-02-01
- Express代理转发服务器实现 2023-08-08
- AJAX应用实例之检测用户名是否唯一(实例代码) 2023-02-14
- vue项目接收二进制流展示表格 2023-10-08
- 浅谈重绘和回流的解析 2022-11-20
- CSS解决未知高度垂直居中的问题 2022-10-16
- 1 Vue - 简介 2023-10-08
- js的onload事件及初始化按钮事件示例代码 2023-11-30