做一个网站.它由一个位于中心的主容器和一个侧边栏组成.我只知道如何使侧边栏位于屏幕的最左边或最右边.不过,我想要做的是使侧边栏位于主容器的左侧.有没有办法做到这一点?

侧边栏只是一个弹性框,里面有几个链接和图片.

#container {
  background-color: deepskyblue;
  width: 500px;
  margin: auto;
  padding: 100px;
}

#sidebar {
  background-color: red;
  width: 200px;
  padding: 10px
}
<div id="sidebar" style="float: left">
  <p>Sidebar</p>
</div>
<div id="container">
  <p>Container</p>
</div>

我try 使用float:left,但这只会使侧边栏移动到页面的最边缘.我需要的是侧边栏,这样就可以粘在容器上了.

enter image description here

Diagram of what I have vs what I want

推荐答案

如果你想让容器居中,那么你可以使用css表格来创建3列.我们使两个侧柱1fr的宽度相等,那么中间的柱就是fit-content.然后我们可以使用align-self将侧杆推到容器的边缘.CSS tricks在网格上有一个很好的入门读物,凯文·鲍威尔在youtube上有一个有用的视频

示例如下:

body {
  font-family: "Comic Sans MS", "Comic Sans", cursive;
}

/* we've enclosed the two divs in to wrapper so we can use CSS grid */
.wrapper {
  display: grid;
  grid-template-columns: 1fr fit-content(0) 1fr;
  align-items: start; /* place items to the top of the container */
}

#container {
  aspect-ratio: 1/1;
  background-color: deepskyblue;
  width: 150px;
  margin-right: auto;
  padding: 100px;
}

#sidebar {
  justify-self: end; /* push the sidebar to the right so it butts up next to the container */
  background-color: #ed1c24;
  width: 75px;
  padding: 10px;
}

/* just some prettification */
.wrapper > div {
  border: 2px solid black;
  display: grid;
  place-items: center;
}
<div class="wrapper">
  <div id="sidebar">
    <p>Sidebar</p>
  </div>
  <div id="container">
    <p>Container</p>
  </div>
</div>

Html相关问答推荐

打印pdf时100 vh迪夫有半页高

传单自定义标记(divIcon)html/css不适用

z—index总是 destruct 我的头,我该如何修复它?

UseEffect()从不调用preact

用于删除页面页眉上的超链接的CSS

我希望创建一个对角手风琴与不同的内容(文本和图像)在其正常状态和其他元素悬停

如何从elementor中的滑块中获取文本?

如何用背景色填充边框半径创建的间隙

如何在css中在span中绘制圆弧?

为什么一个 CSS 网格框比其他网格框低?

如何修剪 flex: 1 内的垂直文本?

复制两个

会产生一个空行;复制

元素不会

如何创建淡出研磨背景

Tailwind 网格行高度可防止拉伸到最高行的所有相同高度

在HTML请求中添加源URL

图像比预期宽的网格列

如何为某些行具有 rowspan 的表的每个奇数行着色

如何在 bootstrap 程序导航栏中居中搜索图标

svg 内容超过元素

图标未定位到右上角