如何讓input的高度增加同時保持文字在底部?

如何讓input的高度增加同時保持文字在底部?

讓文本在高 input 框中底部對齊的技巧

網頁開發中,常常需要創建高度較大的輸入框 (input),并讓其中的文本位于底部,而非默認的垂直居中。本文介紹幾種實現此效果的方法。

問題:文本垂直居中

一個高度為 60px 的 input 框,其文本默認垂直居中顯示。我們需要將其調整到底部。

解決方案:利用 css

無需使用 padding,我們可以通過巧妙的 CSS 布局來實現。方法是隱藏 input 的默認邊框,然后用一個帶有邊框的容器包裹 input,并將其定位到容器底部。

步驟:

  1. 隱藏 input 默認邊框: 使用 border: none; 去除 input 的默認邊框。

  2. 創建帶邊框的容器: 創建一個 div 容器,設置其高度和邊框樣式。

  3. 將 input 定位到容器底部: 使用 position: absolute; 和 bottom: 0; 將 input 絕對定位到容器底部。

代碼示例:

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container {   height: 60px;   border: 1px solid #ccc;   position: relative; /* 關鍵:使絕對定位的子元素相對于此容器定位 */ } input {   height: 100%;   border: none;   position: absolute;   bottom: 0;   width: 100%;   box-sizing: border-box; /* 確保內邊距和邊框包含在元素的總寬度和高度內 */ } </style> </head> <body>   <div class="container">     <input type="text" placeholder="請輸入文本">   </div> </body> </html>

通過以上方法,即使 input 高度增加,文本也會始終保持在底部。 box-sizing: border-box; 確保了 input 的高度計算包含了邊框和內邊距,避免了高度計算上的偏差。

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享