我希望我的侧边栏位于主块和标题的左侧,这样当窗口大小改变时,所有块都会一起移动,但是,每当我将其位置从固定更改为相对/粘性时,它就会下降到页面底部。 或者,侧边栏可以保持固定,但我需要找到一种方法来阻止其他块在窗口大小变化时进入其下方。
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel ="stylesheet" href="css/main.css">
<title>Homepage</title></head>
<body>
<div class="header"><div class="element" style="display: flex;"><div class="container">
<button class="button" >1</button>
<button class="button" >2</button>
<button class="button" >3</button>
</div></div></div>
<div class="main"><div class="element">
<h1>TestText</h1>
<p>TestText</p>
<h1>TestText!</h1>
</div></div>
<div class="sidebar"><div class="element"><div class="container">
<p>TestText</p>
<a href="about.html" target="_blank" title="click here~" >
<button class="button">!</button>
</a>
<p><button class="button">!!</button></p>
<p><button class="button">!!!</button></p>
</div></div></div>
</body>
</html>
CSS
body {background-color: #1c1f2b;
margin: 0;
padding: 0;
min-height: 100vh;
font-family: Humaroid;
srs:url(/fonts/Humaroid.otf) format("opentype");
font-size: 1.25rem;
word-break: break-all;}
.container{margin-left: auto;
margin-right: auto;
position: center;}
.sidebar {
color: #FED2C7;
text-shadow:
-1px -1px 0 #704935,
1px -1px 0 #704935,
-1px 1px 0 #704935,
1px 1px 0 #704935;
height: 100%;
width: 160px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
overflow-x: hidden;
padding-top: 20px;
background-color: #faf4e6;
margin-right: 20px;
}
.header {background-color: #faf4e6;
height: 90px;
width: 940px;
position: relative;
margin: 0 auto;
padding-bottom: 10px
}
.main{ width: 940px;
height: 80vh;
margin: 0 auto;
padding: 30 px;
background-color: #faf4e6;}
.element{
font-weight: 400;
text-align: left;
margin: 1em;}
我看到有人提到这个问题可能是由于 div 块保持打开状态引起的,但对我来说似乎并非如此。 我还尝试向侧边栏添加底部边距,但这没有任何作用。
不要尝试编写自定义 CSS,而是尝试参考已知的做法(谷歌页面网格布局)。例如,其中之一是:https://www.w3schools.com/css/css_grid.asp.
但是,他们的风格与你的不符,但你可以尝试这个html/css:
<!DOCTYPE html>
<html>
<head>
<style>
.item1 { grid-area: header; }
.item2 { grid-area: menu; }
.item3 { grid-area: main; }
.item5 { grid-area: footer; }
.grid-container {
display: grid;
grid-template-areas:
'menu header header header header header'
'menu main main main main main'
'menu footer footer footer footer footer';
gap: 10px;
background-color: #2196F3;
padding: 10px;
}
.grid-container > div {
background-color: rgba(255, 255, 255, 0.8);
text-align: center;
padding: 20px 0;
font-size: 30px;
}
</style>
</head>
<body>
<h1>Grid Layout</h1>
<p>The CSS Grid Layout Module offers a grid-based layout system, with rows and columns, making it easier to design web pages without having to use floats and positioning:</p>
<div class="grid-container">
<div class="item1">Header</div>
<div class="item2">Menu</div>
<div class="item3">Main</div>
<div class="item5">Footer</div>
</div>
</body>
</html>
您可以使用 Flexbox 实现类似的效果(同样,您可以通过 google 搜索 Flex 页面布局)。另外我建议您使用 css 框架,例如 Bootstrap 或 Tailwind。