如何实现<div>中元素上下对齐

本文介绍了一种使用CSS的height和line-height属性实现文本上下居中的方法。关键是首先为父div设置高度,然后使line-height等于该高度。

     <div id="about_daohang_right_title">

         <h4 id="about_daohang_right">产品展示</h4>

</div>

要实现的功能就是将“产品展示”进行在div中进行上下居中对齐,解决的办法就是使用line-height属性,但是在使用line-height属性之前,首先要给父类的<div>加上height属性,这是实现上下居中对齐的前提,设置好height属性后,此时的line-height的值就是等于谷类的height属性值。

也就是通过heightline-height两个属性值就设置好了上下对齐的方式。

<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>页面布局示例</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } /* 外层容器 */ .container { margin: 20px auto; /* 居中显示,上下留间距 */ padding: 15px; /* 容器内边距 */ } /* 通用区块样式:虚线边框、浅灰背景、居中文字 */ .section { border: 1px dashed #ccc; background-color: #f5f5f7; text-align: center; padding: 20px; margin-bottom: 5px; /* 区块间间距 */ } /* top区域 */ .top { height: 60px; } /* banner区域 */ .banner { height: 100px; weight: 600px; } /* 内容区容器 */ .content { justify-content: center; margin-bottom: 5px; } /* 行容器 */ .row { display: flex; gap: 5px; /* 列之间的间距 */ margin-bottom: 10px; /* 行之间的间距 */ } /* 内容项(每行4个) */ .item { flex: 1; /* 平均分配宽度 */ height: 100px; line-height: 120px; border: 1px dashed #ccc; background-color: #f5f5f7; text-align: center; } /* footer区域 */ .footer { height: 80px; line-height: 80px; padding: 0; margin-bottom: 0; /* 取消底部间距 */ } </style> </head> <body> <div class="container"> <!-- top区域 --> <div class="section top"></div> <!-- banner区域 --> <div class="section banner"></div> <!-- 内容区(两行四列) --> <div class="content"> <!-- 第一行 --> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> <!-- 第二行 --> <div class="row"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div> <!-- footer区域 --> <div class="section footer"></div> </div> </body> </html>注释
11-08
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值