使用display:table布局时单元格垂直对齐异常问题求助
问题修复方案
这个问题的核心是**vertical-align属性的作用对象搞错了**,再加上多余的 clearfix 代码干扰布局,调整后就能解决:
问题分析
vertical-align: middle是给display: table-cell元素设置的,你加到了display: table的.container上,完全没起作用;- 图片默认的
vertical-align是baseline,会让左侧单元格的基线和右侧内容对齐,视觉上显得右侧内容偏下; .container里的content: ""和clear: both是清除浮动的写法,和display: table布局不兼容,属于多余代码。
修复后的代码
.container { display: table; margin: 0 auto; border-radius: 5px; border: 5px solid #ff656c; padding: 0 20px; width: inherit; } #column1 { display: table-cell; vertical-align: middle; /* 让单元格内容垂直居中对齐 */ } #column2 { display: table-cell; width: 50%; vertical-align: middle; /* 让单元格内容垂直居中对齐 */ padding-left: 20px; /* 给左右列添加间距,提升美观度 */ } #scope { width: 100%; }
<div class="container"> <div id="column1"> <img id="scope" src="https://cdn.pixabay.com/photo/2018/07/08/19/59/blood-pressure-3524615_960_720.jpg"> </div> <div id="column2"> <h2>Welcome to PATHFINDER</h2> <p>For people with heart failure, GPs are crucial in initiating and optimising dosages of recommended medications</p> <p>The National Heart Foundation of Australia and the Cardiac Society of Australia and New Zealand published guidelines that outline the goal of pharmacological therapy for persons with heart failure with reduced ejection fraction (HFrEF), and how to up-titrate these medicines.</p> <p>PATHFINDER aims to provide assistance to GPs to identify the most appropriate medicines and dosages for each patient</p> </div> </div>
额外说明
- 如果想让左右列宽度更均衡,可以给
#column1也设置width: 50%,实现两列各占一半的布局; - 移除了
#scope的padding-right,换成给#column2加padding-left,避免图片布局被内边距干扰,间距也更合理。
内容的提问来源于stack exchange,提问作者FHS
相关产品推荐
相关产品推荐

