【前端】css布局html页面之inline-block布局错位解决方法

146 阅读1分钟

我正在参加「掘金·启航计划」

本篇文章中,主要讲讲前端布局的情况
对于,对于刚接触前端开发的小伙伴来说,布局是一个比较重要的知识点,如果知识点理解不到位,那么很容易出现布局错位的情况

【场景如下】

1)编写css和html

<div class="" style="padding:10px;">
    <div style="display:inline-block;">
        <div style="float:left;height:35px;line-height:35px;padding:0 10px;background:#ccc;border:1px solid #ccc;">
            <label>one</label>
        </div>
        <div style="float:left;height:35px;line-height:35px;padding:0 10px;background:#eee;border:1px solid #ccc;">
            <span class="">two</span>
        </div>
    </div>
 
    <div style="display:inline-block;height:35px;line-height:35px;padding:0 10px;border:1px solid #0ccdff;background:#0ccdff;color:#fff;cursor:pointer;">
        <span>按钮</span>
    </div>
</div>

2)页面效果,两个行内元素出现错位

image.png

3)解决方案 使用垂直对齐的样式,vertical-align:middle

1656119555257.jpg

1656119562307.jpg

4)知道解决方法,但也要知道为什么会出现,这样能够加深理解,快速解决问题

把第一个inline-block内部div的float浮动去掉,效果如下

第二个inline-block会和第一个inline-block内部的最后一个div对齐

image.png

猜想,如果我只给第二个inline-block设置垂直水平顶部对齐vertical-align:top,那么有按钮则会和one对齐

image.png

5)综上分析,以上解决方法,只需要给按钮这个div设置垂直水平顶部对齐vertical-align:top样式即可

  • 代码
    <div class="" style="padding:10px;">
        <div style="display:inline-block;">
            <div style="float:left;height:35px;line-height:35px;padding:0 10px;background:#ccc;border:1px solid #ccc;">
                <label>one</label>
            </div>
            <div style="float:left;height:35px;line-height:35px;padding:0 10px;background:#eee;border:1px solid #ccc;">
                <span class="">two</span>
            </div>
        </div>
 
        <div style="display:inline-block;height:35px;line-height:35px;padding:0 10px;border:1px solid #0ccdff;background:#0ccdff;color:#fff;cursor:pointer;vertical-align: top;">
            <span>按钮</span>
        </div>
    </div>

image.png