1. 程式人生 > 其它 >解決父元素的padding對子元素的input失效問題

解決父元素的padding對子元素的input失效問題

技術標籤:前端csshtmlcss3

文章目錄

問題描述

在一個含有padding的div元素中包含一個input標籤和一個icon,但是input元素顯示異常。(具體表現為父元素的padding對子元素的input失效)
異常效果圖:
在這裡插入圖片描述
案例程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Taoism</title>
	<style>
		* {
			box-sizing: border-box;
		}

		.container {
			height: 64px;
			width: 300px;
			padding-top: 16px;
			padding-bottom: 16px;
			background-color: palevioletred;
		}

		.input {
			height: 32px;
			width: 200px;
		}

		.icon {
			display: inline-block;
			height: 32px;
			width: 32px;
			background-color: aquamarine;
		}
	</style>
</head>

<body>
	<div class="container">
		<input class="input" type="text">
		<div class="icon"></div>
	</div>
</body>

</html>

解決方案

方案一

由於input標籤預設的display為inline-block並且icon的display也為inline-block,現在我們想要改變input的垂直對齊方式,此時不難想要使用此css屬性:vertical-align
給input標籤新增以下一行程式碼即可使其行類元素居中對齊:

vertical-align: top;

效果圖如下:
在這裡插入圖片描述

方案二

我們知道產生此異常的原因是由於display: inline-block,如果將其改成display: block則不會出現此異常,但是我們目的就是想將這兩個元素在一行內居中顯示,所以此時就需要使用另一種css屬性:float


修改後的完整程式碼如下:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Taoism</title>
	<style>
		* {
			box-sizing: border-box;
		}

		.container {
			height: 64px;
			width: 300px;
			padding-top: 16px;
			padding-bottom: 16px;
			background-color: palevioletred;
		}

		.input {
			height: 32px;
			width: 200px;
			display: block;
			float: left;
		}

		.icon {
			display: block;
			float: left;
			height: 32px;
			width: 32px;
			background-color: aquamarine;
		}
	</style>
</head>

<body>
	<div class="container">
		<input class="input" type="text">
		<div class="icon"></div>
	</div>
</body>

</html>

效果圖如下:
在這裡插入圖片描述

更多方案

以上兩種方案都是不改變父元素佈局的方式來實現預期的效果,如果允許更改父元素的樣式則還有更多的實現方案,比如flex佈局,定位佈局等等。

結語

正所謂條條大路通羅馬,面對css佈局所產生的bug時,只要能夠掌握足夠多的css屬性,至少總能夠找到一種比較滿意的解決方案。