Web前端培训:两个div在同一行可以实现吗?

我们在写页面的时候经常会遇到需要将两个div盒子同行显示的情况,那么“两个Div同行显示”该如何显示呢?一般两个div同行显示可以用float: left和display: inline_block来实现,下面我们分别介绍。

首先我们先来看,没有同行显示的两个div什么显示效果。

代码:

<div class="div1">div1</div>
<div class="div2">div2</div>

CSS样式:

.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);
}

方法1:浮动

通过浮动使两个div在同一行显示,两个div同时左浮动(float: left)或者有浮动(float: right)。

CSS样式:

.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);
}

方法2:display: inline-block转为行内块

使用display: inline-block将两个盒子转为行内块,实现两个div同行显示。

代码:

<!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">
    <title>两个div盒子一行显示</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 class="div1">div1</div>
    <div class="div2">div2</div>
</body>
</html>

效果

注意:使用display: inlien-block转为行内块之后,两个行内块儿元素之间有缝隙。

产生缝隙的原因:

元素被当成行内元素排版的时候,元素之间的空白符(空格、回车换行等)都会被浏览器处理,根据white-space的处理方式(默认是normal,合并多余空白),我们这里是因为div1和div2两个盒子代码的之间的"回车"被处理成为了缝隙。我们将两个div的代码写在一行就可以解决了,如下:

<div class="div1">div1</div><div class="div2">div2</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值