![](/img/trans.png)
[英]HTML make child div expand beyond parent div (without width: 9999px)
[英]Contents inside a parent div expand beyond the width
我需要你的幫助。
看來我的孩子的div(文本區域和文本)超出了邊界:
這是期望的結果:
這是HTML / CSS:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
#one {
width: 800px;
border: 1px solid red;
}
#two {
text-align: right;
}
#three {
}
#field {
width: 100%;
}
</style>
</head>
<body>
<div id="one">
<div id="two">text to the right</div>
<div id="three"><textarea id="field"></textarea>
</div>
</body>
</html>
邊框和填充添加到寬度上。 由於您的寬度為100%,因此會在字段上添加填充和邊框。
因此,如果寬度為“ 1”的120像素,則邊框將增加2像素,填充將增加幾像素。
如果您從“三個”中減去一些空間,則可以實現此目的。
#three {
width:794px;
}
以下內容也適用於大多數瀏覽器。
#field {
width: 100%;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
}
否則,您可以從文本區域中刪除邊框和填充。 說實話,有很多方法可以做到這一點。
textarea
邊框和填充是您的問題。 兩種選擇都與textarea的CSS有關。 正如您從下面的代碼中看到的那樣,我還為#one
添加了相對位置,以確保它可以在您的頁面上下文中使用,因此textarea的寬度實際上將由此容器確定大小。
設置適當的box-sizing
以便包括邊框和填充( JSFiddle ):
#one { width: 800px; border: 1px solid red; position: relative; } #two { text-align: right; } #three { } #field { width: 100%; box-sizing: border-box; /* let's also add these for cross-browser safety */ border-width: 1px; padding: 2px; }
將width
設置為小於100%( JSFiddle )
#one { width: 800px; border: 1px solid red; } #two { text-align: right; } #three { } #field { /* (1px border + 2px padding) × 2 for left and right side */ width: calc(100% - 6px); }
它超出邊界的原因是,它采用border:2px;
您設置width: 100%
#field
文本區域的width: 100%
為width: 100%
。 默認情況下,textarea的border
和padding
也具有非零值。 因此,畢竟您的textarea寬為800px (繼承自.three
)+ 4px邊框+ 2px邊框= 806px (但可能略有不同,具體取決於您使用的瀏覽器)。
將#field
CSS修改為此
#field {
width: 100%;
margin: 0;
padding: 0;
border: 0;
}
我還設置了margin: 0
只是為了確保某些瀏覽器不會將其設置為非零值。
經典的盒子模型將寬度與邊距,填充和邊框相加。
在這種情況下,將您的textarea設置為另一種計算寬度的方法,即將box-sizing設置為border-box(寬度是適當的寬度,沒有邊距,內邊距和邊框)
#field { width: 100%; -webkit-box-sizing:border-box; }
(您可以添加所需的前綴,-moz,-ms,-o ...)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.