Problem:
We have a container element with % to define the width. In the container, we need to display another element that fullfills this container. The conained element need some border or padding. If we define the contained element's width to 100%, then the border and padding would make the contained element bigger than the container, because the actual width of the element would be the width+padding+border.
Solution:
Add a blocked element like <div> to wrap the contained element. Move the padding, margin or border of the contained element to the wrapper <div>. Set the contained element with width 100%, no border, margin, padding. The wrapper div will fullfill the outer container by the block feature.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.container {
width: 30%;
height: 200px;
background-color: #adff2f;
padding: 10px;
}
.blocked_wrapper {
border: 1px solid #939598;
height: 20px;
}
.contained {
width: 100%;
height: 100%;
border: 0 none;
}
</style>
</head>
<body>
<div class="container">
<div class="blocked_wrapper">
<input type="text" class="contained"/>
</div>
</div>
</body>
</html>
If you use CSS3, it would be much more easier. Border-box would completely solve this prblem.
.sizing {
padding: 0px 4px;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
}

本文介绍了一种使用CSS解决容器内元素宽度溢出问题的方法,通过包裹元素并调整边界盒模型实现精确布局。
2万+

被折叠的 条评论
为什么被折叠?



