首页 > 解决方案 > 侧边栏切换 - 侧边栏切换时主要内容不会拉伸到全宽

问题描述

我在一个名为 wrapper 的父元素内有一个带有侧边栏和主要内容的布局,还有一个用于切换相对于侧边栏绝对定位的侧边栏的按钮。但是当侧边栏关闭时,主要内容不会保持全宽。我发现将侧边栏固定为固定可以解决问题,但我不希望它被修复,有没有办法在不为侧边栏固定位置的情况下实现这一点。我使用 translate 来切换侧边栏。

Jsfiddle - https://jsfiddle.net/wu1zfg35/

这是CSS。工作代码可以在 js fiddle 链接中找到

body {
  margin: 0;
}

.wrapper{
  display: flex;
  height: 100vh;
}

.sidebar {
  position: relative;
  /* position: fixed;  */
  width: 350px;
  height: 100%;
  background-color: red;
  transition: all 0.5s ease 0s;
  -webkit-transition: all 0.5s ease 0s;
  -webkit-transform: translate3d(-100%, 0px, 0px);
  transform: translate3d(-100%, 0px, 0px);
}

.main-content {
  width: 100%;
  background-color: yellow;
  transition: all 0.5s ease 0s;
  -webkit-transition: all 0.5s ease 0s;
}

.hide-customize-tab {
  position: absolute;
  display: flex;
  top: 50%;
  right: -25px;
  align-items: center;
  justify-content: center;
  height: 25px;
  width: 25px;
  background-color: black;
  transition: all 0.5s ease 0s;
  -webkit-transition: all 0.5s ease 0s;
  cursor: pointer;
}

.hide-customize-tab .close-button {
  display: none;
  height: 10px;
  width: 7px;
}
.hide-customize-tab .open-button {
  height: 10px;
  width: 7px;
}

.wrapper.sidebar-opened .sidebar {
  -webkit-transform: translate3d(0px, 0px, 0px);
  transform: translate3d(0px, 0px, 0px);

}

.wrapper.sidebar-opened .sidebar .hide-customize-tab {
  right: -15px;
}

.wrapper.sidebar-opened .sidebar .hide-customize-tab .open-button {
  display: none;
}

.wrapper.sidebar-opened .sidebar .hide-customize-tab .close-button {
  display: block;
}

.wrapper.sidebar-opened .main-content {
  /* margin-left: 350px; */
  width: calc(100% - 350px);
}

标签: javascripthtmlcss

解决方案


移除宽度:350px;从 .sidebar 并将其添加到 .wrapper.sidebar-opened .sidebar

所以代码将是

.sidebar {
    width: 0;
}

.wrapper.sidebar-opened .sidebar {
    width: 350px;
}

推荐阅读