文章最后更新时间:2024年08月10日已超过844天没有更新。
如何将两个div盒子在同一行显示的css样式
关键词:两个div在同一行显示,css浮动样式,css行内块样式
我们在写页面的时候经常会遇到需要将两个div盒子同行显示的情况,那么“两个Div同行显示”该如何显示呢?一般两个div同行显示可以用float:left和display:inline_block来实现,下面我们分别介绍。
首先我们先来看,没有同行显示的两个div是什么显示效果?
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>测试_cuinew.com</title>
<style>
.div1 {
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(26, 135, 238);
}
.div2 {
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(7, 194, 178);
}
</style>
</head>
<body>
<div>div1</div>
<div>div2</div>
</body>
</html>没有同行显示的两个div显示效果:

方法1:添加浮动(float)样式
通过css浮动样式使两个div盒子在同一行显示,两个div盒子同时添加左浮动(float: left)样式或者同时添加右浮动(float: right)样式。
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>测试</title>
<style>
.div1 {
float: left; /* 左浮动样式 */
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(26, 135, 238);
}
.div2 {
float: left; /* 左浮动样式 */
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(7, 194, 178);
}
</style>
</head>
<body>
<div>div1</div>
<div>div2</div>
</body>
</html>添加浮动css样式后,左浮动的两个div显示效果:

方法2:转为行内块
使用转为行内块(display: inline-block)样式将两个盒子转为行内块,实现两个div盒子同行显示。
HTML代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>测试</title>
<style>
.div1 {
display: inline-block; /* 转为行内块 */
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(26, 135, 238);
}
.div2 {
display: inline-block; /* 转为行内块 */
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
color: aliceblue;
background-color: rgb(7, 194, 178);
}
</style>
</head>
<body>
<div>div1</div>
<div>div2</div>
</body>
</html>修改为display: inline-block; 的显示效果:

注意:使用display: inlien-block转为行内块之后,两个行内块儿元素之间有缝隙。
产生缝隙的原因:
元素被当成行内元素排版的时候,元素之间的空白符(空格、回车换行等)都会被浏览器处理,根据white-space的处理方式(默认是normal,合并多余空白),我们这里是因为div1和div2两个盒子代码的之间的"回车"被处理成为了缝隙。我们将两个div的代码写在一行就可以解决了,如下:
<div>div1</div><div>div2</div>
文章版权声明:除非注明,否则均为崔牛网原创文章,转载或复制请以超链接形式并注明出处。


