如何在不切断边框的情况下给body标签添加边框?

4
我是一名初学者,想要在学习过程中可视化我所做的html和css更改,因此我想在添加的所有元素周围加上边框。
问题:当overflow设置为hidden时,html/body元素周围的蓝色边框被裁剪,在底部和右侧边框不完全显示。
为什么即使将其宽度和高度设置为100%,边框也会超出html页面?
HTML
<!DOCTYPE html>
    <html>
    <head>
        <title> Practice Webpage </title>
        <link href="stylesrevised.css" rel="stylesheet" type="text/css" >
    </head>

    <body></body>
    </html>

CSS

html,body{
    width: 100%;
    height: 100%;
    margin: 0; /* Space from this element (entire page) and others*/
    padding: 0; /*space from content and border*/
    border: solid blue;
    border-width: thin;
    overflow:hidden;
    display:block;
}

这里是生成的网页


1
我建议使用outline: 1px solid blue;而不是border。边框不仅会影响盒模型,正如下面的答案所说,还可能会防止边距折叠。 - Web_Designer
@Web_Designer,如果在 body 或者 html 上使用 outline 属性会导致其在可视窗口外无法显示。如果想要看到它,您需要使用 outline-offset: -1px 属性来进行设置。请务必将偏移量设置为轮廓线宽度的负数(例如:outline: 17px solid blue; outline-offset: -17px)。 - pbarney
2个回答

7

欢迎踏上编程之旅!在你的css中,添加以下内容:box-sizing: border-box;

这将使你的元素适应所规定的宽度和高度。

html,body{
    width: 100%;
    height: 100%;
    margin: 0; /* Space from this element (entire page) and others*/
    padding: 0; /*space from content and border*/
    border: solid blue;
    border-width: thin;
    overflow:hidden;
    display:block;
    box-sizing: border-box;
}
<!DOCTYPE html>
    <html>
    <head>
        <title> Practice Webpage </title>
        <link href="stylesrevised.css" rel="stylesheet" type="text/css" >
    </head>

    <body></body>
    </html>


非常感谢!已经解决了。我应该将其添加到所有我想要可视化的元素中吗?(div、图像等) - Zach
@Zach 那个问题的答案是 - 这取决于情况。如果您想看到没有填充和边框厚度影响元素大小的元素,则是的。尝试两种方式 - 设置和未设置。在开发环境中,通过将填充2、边框宽度2和边距*2添加到宽度/高度来计算元素的大小和位置。即使如此,这还取决于您要创建什么。如果您只想可视化您的元素,则每次使用它都不会有害。使用 * { box-sizing: border-box;} - wlh

1
你的 overflow: hidden; 正是导致问题的原因,边框的默认设置为 content-box,这会增加元素的宽度和高度,例如如果你有一个宽度为 100px 的 div 并添加了 1px 的边框,它的实际大小将是 102px。
你可以通过使用 box-sizing: border-box; 来解决这个问题,这会使边框被添加到元素内部。

html,body{
    width: 100%;
    height: 100%;
    margin: 0; /* Space from this element (entire page) and others*/
    padding: 0; /*space from content and border*/
    border: solid blue;
    border-width: thin;
    display:block;
    box-sizing: border-box;
}

如果您想在整个网站中使用所有边框,可以使用此方法,这样可以避免每次添加边框时都要设置。
*, *:before, *:after {
  box-sizing: border-box;
}

@Zach 我已经更新了我的答案*,将捕获您添加的所有未来边框,因此您不必继续添加该代码。您想要在周围有蓝色边框的任何内容都需要添加border: 1px solid blue;代码。 - Bosc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接