css解決display:inline-block;產生的縫隙(間隙)


今天在做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>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM