您现在的位置是:首页 > Javascript
当前栏目
前端面试 【CSS】— 使用 display:inline-block 会产生什么问题?解决方法?
2023-03-14 22:48:07 时间
1. 产生的问题描述
两个display为inline-block元素放到一起会产生一段空白。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.container {
width: 800px;
height: 200px;
}
.left {
font-size: 14px;
background: red;
display: inline-block;
width: 100px;
height: 100px;
}
.right {
font-size: 14px;
background: blue;
display: inline-block;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="left">左</div>
<div class="right">右</div>
</div>
</body>
</html>
如上代码所示,运行后效果如下:
2. 问题产生的原因
元素被当成行内元素排版的时候,元素之间的空白符都会被浏览器处理,根据CSS中 white-space 属性的处理方式(默认是normal,合并多余空白),原来HTML代码中的回车换行被转成一个空白符,在字体不为0的情况下,空白符占据一定宽度,所以 inline-block 的元素之间就出现了空隙。
3. 问题的解决办法
1. 将子元素标签的结束符和下一个标签的开始符写在同一行 或 把所有子标签写在同一行;
<div class="container">
<div class="left">
左
</div><div class="right">
右
</div>
</div>
2. 父元素中设置font-size为0,在子元素上重置正确的 font-size;
<style>
.container {
width: 800px;
height: 200px;
/* 父元素字体设置为0 */
font-size: 0;
}
.left {
font-size: 14px;
background: red;
display: inline-block;
width: 100px;
height: 100px;
}
.right {
font-size: 14px;
background: blue;
display: inline-block;
width: 100px;
height: 100px;
}
</style>
<div class="container">
<div class="left">左</div>
<div class="right">右</div>
</div>
3. 为子元素设置float为left;
<style>
.container {
width: 800px;
height: 200px;
}
.left {
/* 添加浮动 */
float:left;
font-size: 14px;
background: red;
display: inline-block;
width: 100px;
height: 100px;
}
.right {
/* 添加浮动 */
float:left;
font-size: 14px;
background: blue;
display: inline-block;
width: 100px;
height: 100px;
}
</style>
<div class="container">
<div class="left">左</div>
<div class="right">右</div>
</div>
相关文章
- 使用 EC2 Image Builder 实现 OS 映像构建管道自动化
- python3 xml模块
- 如何在 AWS 上构建并行文件系统 BeeGFS
- Python XML解析
- Java Script变量
- Python Flask,abort函数
- Amplify Framework 更新 — 快速为您的 Web 和移动应用程序添加机器学习功能
- 支持 Apache 软件基金会
- python logging模块练习
- OpenSource | Amazon 加入 W3C
- java/Spring/IOC
- python_xml模块处理
- Python HTML操作(HTMLParser)
- java gui组件_JAVA GUI界面组件学习
- http rest JAVA_JAVA发HTTP请求 - RestTemplate 案例
- python unittest生成html报告_python+unittest框架生成HTML测试报告
- 快速构建一个用本地网络发送和接收消息的APP
- 2021年,排名前 15 的 Vue 后台管理模板
- Spring Boot一键换肤,so easy!
- 美国或将所有设计14nm以下中国芯片公司纳入出口管制?