標籤:flex 布局 20px 設定 水平滑動 alt color nbsp justify
今天在做H5的水平滑動卡片時用到了display:inline-block;卻發現處在同一水平線上的元素之間居然產生了縫隙,這很顯然不是我想要的效果,所以我就換成了左浮動,這樣縫隙的問題是解決了,但是需要設定父元素的寬度才能實現水平左右滾動,這樣又增加了代碼量,因為卡片的個數不固定,需要即時設定其父元素的寬度,就要用到js,所以代碼量增加了,也不是最好的選擇。看來最好的解決辦法就是用到display:inline-block;了,於是縫隙的問題就出現了。代碼如下:
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>document</title><style>*{margin:0;padding:0;}.box{overflow-x:auto;background:#fff;white-space:nowrap;}.box span{display:inline-block;width:100px;height:30px;line-height:30px;text-align:center;background:#f00;color:#fff;}</style></head><body><div class="box"> <span>111</span> <span>111</span> <span>111</span> <span>111</span></div></body></html>
效果如下:
這個縫隙很明顯存在,據說這種表現是符合規範的應該有的表現,是換行造成的空白符導致的。但這效果很顯然不是我們想要的,我們想要的縫隙是我們根據自己的實際需求而設定的邊距。那麼該如何消除產生的這個縫隙呢?辦法有三:
方法一:元素之間不換行,代碼如下:
<div class="box"> <span>111</span><span>111</span><span>111</span><span>111</span></div>
效果如下:
方法二:給其父元素設定font-size:0;給其自身設定實際需要的字型大小大小。不好的地方就是有些瀏覽器有設定最小字型,像chrome和opera,但是現在的chrome好像沒有這個設定了,代碼如下:
**css:**.box{overflow-x:auto;background:#fff;white-space:nowrap;font-size:0;}.box span{display:inline-block;width:100px;height:30px;line-height:30px;text-align:center;background:#f00;color:#fff;font-size:14px;}**html**<div class="box"> <span>111</span> <span>111</span> <span>111</span> <span>111</span></div>
效果如下:
方法三: flex 布局
<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>document</title><style>* {margin: 0;padding: 0;}.box {display: flex;justify-content:space-between;}.box span {width: 100px;height: 30px;line-height: 30px;text-align: center;background: #f00;color: #fff;font-size: 20px;}</style></head><body><div class="box"><span>111</span><span>111</span><span>111</span><span>111</span></div></body></html>
css解決display:inline-block;產生的縫隙(間隙)