通过使用CSS创建不相等的列,我试图将页面分成一个包含主内容的大列(.leftcolumn
)和用作侧边栏的较小列(.rightcolumn
)。 但是,侧边栏会被推到主内容的下面,除非我将其中一栏的宽度比它的宽度小2%。
我试着按照这个答案的建议切换标签的顺序,但是没有效果。 我还尝试给主要内容一个display:flex
属性,正如这里的答案所建议的,但这只是将主要内容中的两个示例帖子沿一行组合在一起,而对侧边栏没有影响。 我测试的其他一些东西是将position:relative
分配给主要内容,将position:absolute
分配给侧边栏,这是这个答案给出的解决方案,但这对实际显示没有影响。 我还尝试了下面@Rajneesh-Tiwari的建议,在侧边栏的父容器下定义z-index:999
,但这也对显示没有影响。
我的代码部分基于w3schools中的一个示例(原始代码在那里运行良好),如下所示:
null
<!DOCTYPE html>
<html>
<head>
<style>
* {
font-family: Verdana;
}
body {
background: #f2f2f2;
padding: 5px;
}
.leftcolumn {
float: left;
width: 75%;
}
.rightcolumn {
background-color: #f2f2f2;
float: left;
padding-left: 20px;
width: 25%;
}
.card {
background-color: white;
border-radius: 8px;
margin-top: 20px;
padding: 20px;
}
.row:after {
clear: both;
content: "";
display: table;
}
@media screen and (max-width: 800px) {
.leftcolumn, .rightcolumn {
padding: 0;
width: 100%;
}
}
</style>
</head>
<body>
<div class="row">
<div class="leftcolumn">
<div class="card">
<h2>HEADING</h2>
<h5>Description</h5>
<p>Text.</p>
</div>
<div class="card">
<h2>HEADING</h2>
<h5>Title description, Sep 2, 2017</h5>
<div class="fakeimg" style="height:200px;">Image</div>
<p>Some text..</p>
<p>Text.</p>
</div>
</div>
<div class="rightcolumn">
<div class="card">
<h2>About Me</h2>
<p>text</p>
</div>
<div class="card">
<h3>Popular Post</h3>
<p>text</p>
</div>
<div class="card">
<h3>Follow Me</h3>
<p>text</p>
</div>
</div>
</div>
</body>
</html>
null
我做错了什么? 我可以将其中一列的宽度减少2%(75%到73%或25%到23%),但是。leftcolumn不会与标题的边缘对齐(从显示的代码中移除,以减少混乱),这让我很困扰。
任何帮助都是非常感激的!
问题是你放在侧边栏上的填充物。 (填充不会影响宽度,所以侧边栏是25%+20px填充,这就是为什么它会被下推的原因)
若要修复此问题,请从侧边栏或左列的宽度中删除(减去)填充。 我喜欢使用calc()来实现这一点。 在下面的例子中,我从。rightcolumn的25%中删除了20px。
width: calc(25% - 20px);
只要记住,您添加的任何填充都会增加总宽度,使其超过100%,这就是为什么它没有工作。 https://www.w3schools.com/cssref/func_calc.asp
null
<!DOCTYPE html>
<html>
<head>
<style>
* {
font-family: Verdana;
}
body {
background: #f2f2f2;
padding: 5px;
}
.leftcolumn {
float: left;
width: 75%;
}
.rightcolumn {
background-color: #f2f2f2;
float: left;
padding-left: 20px;
width: calc(25% - 20px);
}
.card {
background-color: white;
border-radius: 8px;
margin-top: 20px;
padding: 20px;
}
.row:after {
clear: both;
content: "";
display: table;
}
</style>
</head>
<body>
<div class="row">
<div class="leftcolumn">
<div class="card">
<h2>HEADING</h2>
<h5>Description</h5>
<p>Text.</p>
</div>
<div class="card">
<h2>HEADING</h2>
<h5>Title description, Sep 2, 2017</h5>
<div class="fakeimg" style="height:200px;">Image</div>
<p>Some text..</p>
<p>Text.</p>
</div>
</div>
<div class="rightcolumn">
<div class="card">
<h2>About Me</h2>
<p>text</p>
</div>
<div class="card">
<h3>Popular Post</h3>
<p>text</p>
</div>
<div class="card">
<h3>Follow Me</h3>
<p>text</p>
</div>
</div>
</div>
</body>
</html>
如果要使用flexbox,请删除浮动和清除。 然后使父容器(。row)成为一个flex框(display:flex)。 然后,使用flex属性代替column元素上的width属性。 例如,您可以给出左列“flex:5”和右列“flex:1”。
您可以使用
z-index:999
在侧边栏的父容器上。
Z索引用于沿Z轴(即深度维度)定位元素。