`

Blocked Wrapper

 
阅读更多

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>

 

Try it with jsfiddle

 

 

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+ */
}

 

Try it with jsfiddle

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics