如何移除h1与h2标签间空白 实现预期网页头部排版效果
问题原因
设置margin、padding为0不生效,核心有3个问题:
- CSS语法错误:h1和h2的
font-size属性只写了属性名没写属性值,会导致浏览器解析CSS时中断,后面写的margin、padding规则在部分浏览器下无法生效 - 浏览器默认行高留白:就算margin、padding为0,标题元素默认的
line-height会给文字上下预留额外空间,两个标题相邻时就会出现视觉上的空隙 - 浮动影响:logo图片设置了左浮动,后续的标题元素没有做适配,容易出现排版偏移
修复方案
- 补全h1、h2的
font-size属性值,按设计需求设置对应字号 - 给h1、h2设置紧凑的
line-height(推荐1~1.2之间),消除文字默认的上下留白 - 给.header容器清除浮动,避免排版错乱;如果需要标题在logo右侧排布,给logo设置右侧外边距留出间距即可
- 两个标题需要不同字体的话,直接分别给h1、h2添加
font-family属性设置即可,互不干扰 - 如果调整后还有极细的空隙,属于字体文件本身自带的上下边距,给h2加1~3px的负
margin-top微调即可
修复后完整代码
body { background-color: white; color: black; font-family: Verdana; } .header { width: 1200px; position: relative; /* 清除内部浮动,避免容器高度塌陷 */ overflow: hidden; } .header img { float: left; /* 按logo实际尺寸调整右侧间距,给标题留出位置 */ margin-right: 12px; } .header h1 { /* 按设计需求调整字号 */ font-size: 2rem; /* 单独设置h1字体 */ font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #666600; /* 紧凑行高消除默认留白 */ line-height: 1.1; font-weight: 700; } .header h2 { /* 按设计需求调整字号 */ font-size: 1rem; /* 单独设置h2字体 */ font-family: Georgia, serif; margin: 0; padding: 0; background-color: #666600; /* 紧凑行高消除默认留白 */ line-height: 1.1; font-weight: 400; /* 仍有空隙时打开下面注释微调数值 */ /* margin-top: -2px; */ }
<body> <div class="header"> <img src="https://kapaifuel.neocities.org/Resources/KaPaiLogo.png" alt="KaPaiLogo" /> <h1>KA PAI FUEL CAFÉ</h1> <h2>Whangaihia to tinana ki te kai / Nourish you body with organic kai</h2> </div> </body>
内容的提问来源于stack exchange,提问作者Chrissy
相关产品推荐
相关产品推荐

