100% Width div's and form elements + padding?

别等时光非礼了梦想. 提交于 2019-12-11 12:26:59

问题


What do I have to do to prevent the following from stretching more than 100%? It obviously stretches to 100% then adds on the padding... Thanks!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <style type="text/css" media="screen">
        #box {
            width: 100%;
            padding: 20px;
            border: 1px solid #000;
        }
        #box input { 
            width: 100%;
            padding: 5px; 
        }
    </style>
</head>
<body>
    <div id="box">
        <form>
            <input type="text" value="" />
        </form>
    </div>
</body>
</html>

回答1:


Your width:100% on the div is altogether unnecessary. Div's are block level elements which automatically expand to 100% of their container. Remove the width:100% from your div declaration and the padding will be contained within the parent container, no scrolling or extended width.

DON'T use a negative margin, that's just adding a hack to achieve something simple.

You can use this rule in general: You almost never have to put width:100% on a div (I can't think off the top of my head why you would unless it was displayed inline or something) because as mentioned above, block level elements always expand to 100% of their container

edit: that was dumb to suggest setting width 100% on a div displayed inline as you can't set the dimensions on an inline element




回答2:


Create a new form rule and move the padding: 20px; declaration to it.

#box {
    width: 100%;
    border: 1px solid #000;
}

form {
    padding: 20px;
}


来源:https://stackoverflow.com/questions/3206784/100-width-divs-and-form-elements-padding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!