我有一个HTML页面,包含以下CSS:
html {
margin: 0;
position: fixed;
width: 100%;
height: 100%;
}
body {
margin: 5rem;
width: 100%;
height: 100%;
position: relative;
}
当我在Chrome中检查body
元素时,我只能"看到"在左侧和顶部应用的边距。底部和右侧似乎迫使页面/布局。这将导致我的一些内部内容(body内部)被截断一半,因为它"离开"屏幕。
另外,没有滚动条出现在布局的任何地方,尽管添加了overflow: scroll
,我无法滚动到"隐藏"的内容。
当然,body里面还有更多的元素,但是布局太大/复杂,无法在这里复制。有哪些东西会导致布局的右边和底部溢出呢?
基本上我不确定为什么边距只在顶部和左侧可见,以及我应该寻找什么样的CSS来导致这种情况。
编辑::此外,如果我将body
更改为margin: 2rem auto
,则空白仅在"顶部"可见,而不是左/下/右。
html
具有position: fixed
,并且与浏览器的宽度和高度相同。因此,当你在body
上使用边距时,顶部和左侧的边距只是把它的内容从html
上推下来。这就是为什么你看不到它的底部和右侧空白。
*,*::before,*::after { box-sizing: border-box; }
.html {
position: fixed;
width: 100%;
height: 100%;
background-color: orange;
font-size: 2rem;
}
.body {
position: relative;
width: 100%;
height: 100%;
margin: 5rem;
background-color: #000;
color: #FFF;
font-size: 2rem;
}
.body::before,
.body::after {
position: absolute;
border: solid 5px;
font-size: 1rem;
}
.body::before {
content: "body top-margin";
width: 100%;
height: 5rem;
bottom: 100%;
border-top: none;
}
.body::after {
content: "body left-margin";
width: 5rem;
height: 100%;
right: 100%;
border-left: none;
}
p {
position: absolute;
top: 0;
left: 0;
margin: 0;
}
<div class="html"><p>html</p>
<div class="body"><p>body</p></div></div>
你的问题是100%的宽度和边距。在主体上设置100%将其设置为窗口宽度的100%,因此应用外边距将主体推离右侧。在这种情况下,你的身体是100%的窗口宽度+ 10rem。你可以做一些像body{width: 90vw; margin: 5vw;}
我喜欢这个解决方案,因为这样的边距缩放客户端大小,加上使用vw使它更清楚,正文宽度百分比是相对于客户端。
作为一种解决方法,你可以尝试使用以下css(这里没有宽度和高度):
body {
top: 5rem;
right: 5rem;
bottom: 5rem;
left: 5rem;
position: absolute;
}
听起来好像你在尝试为你的页面制作窗口/框架外观。看看这个片段。您需要将box-sizing:border-box
设置为您的body
元素,并将边距更改为填充。然后,您将希望使用诸如div
之类的元素作为内容容器。设置容器为height:100%
和overflow:scroll;
。
html {
margin: 0;
position: fixed;
width: 100%;
height: 100%;
}
body {
padding: 5rem;
width: 100%;
height: 100%;
position: relative;
box-sizing:border-box;
}
div {
background: teal none repeat scroll 0 0;
box-sizing: border-box;
height: 100%;
overflow: scroll;
}
<html>
<body>
<div>Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br />Content<br /></div>
</body>
</html>