如何设置一个总是在300像素的div?

时间:2014-05-02 10:25:15

标签: html css

我想设置一个div总是在300像素,即使我改变边框,填充等。我想自动从300px中减去边框,填充值。我怎么能这样做?

3 个答案:

答案 0 :(得分:5)

LIVE DEMO

当你添加box-sizing:border-box时,计算包括填充和边框

.class {
   -moz-box-sizing: border-box; /* firefox - from the 29 version - no need the prefix */
   box-sizing: border-box; /* others */
   width: 300px;
   padding: 10px;
   border: solid 1px black;
}

这是一篇关于旧盒子模型以及如何更新到新边框模型的帖子: Bye Bye Box Model

浏览器支持非常好,您可以在此处看到 - Can I Use Border-box

(在接下来的monthes中你可以删除-moz-box-sizing,firefox 29版本也支持它,没有前缀。)

答案 1 :(得分:1)

您可以使用box-sizing

-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box;    /* Firefox, other Gecko */
box-sizing: border-box;         /* Opera/IE 8+ */

答案 2 :(得分:-2)

我的建议是将它包装在一个封闭的div中,其最大宽度为300px;和溢出:隐藏;

div {
    max-width: 300px;
    overflow: hidden;
}

这样,你div中的内容至少会尽可能地动态,而封闭的div会保护你内容的其余部分。