为什么页眉不以正文边距居中?

  • 本文关键字:正文 html css viewport
  • 更新时间 :
  • 英文 :


下面,我将标题固定在顶部,设置width: 100%并对margin: 10%body元素应用边距。我预计标题将保持在视口的 100% 宽度,但它现在具有左边距,但到达右侧视口的末尾。

* {
box-sizing: border-box;
}



header {
position: fixed;
background-color: #59b1ff;
top: 0;
height: 20px;
width: 100%;
}

body {
margin: 20%;
}

div {
border: 1px solid grey;
}
<header>Header</header>
<main>
<div>Div</div>
</main>

为什么标题没有附加到左侧视口边缘?

为什么标题没有附加到左侧视口边缘?

因为您没有指定希望其左边缘的位置。

您基本上将left保留在默认auto,因此它考虑了该元素在流中的自然位置(如果未定位(。

添加left: 0,它将按照您希望的方式运行。

只需添加left: 0

* {
box-sizing: border-box;
}
header {
position: fixed;
background-color: #59b1ff;
top: 0;
left: 0;
height: 20px;
width: 100%;
}
body {
margin: 20%;
}
div {
border: 1px solid grey;
}
<header>Header</header>
<main>
<div>Div</div>
</main>

实际上问题出在您的标头元素上。每当使用固定或绝对定位时,还必须在固定元素中指定左侧、右侧或顶部(根据您的需要(。

* {
box-sizing: border-box;
}



header {
position: fixed;
background-color: #59b1ff;
top: 0;
height: 20px;
width: 100%;
left:0;  /*Added this*/
right:0; /*Added this*/
}

body {
margin: 20%;
}

div {
border: 1px solid grey;
}
<header>Header</header>
<main>
<div>Div</div>
</main>

尝试添加以下规则:

header {
position: fixed;
background-color: #59b1ff;
top: 0;
left: 0; /* stick the header to the viewport's left */
height: 20px;
width: 100%;
}
body {
position: relative; /* allows the header to be positioned relative to the body */
margin: 20%;
}

只需将 left 属性设置为零。将其设置为默认值,它将采用此元素在流中的自然位置。

最新更新