如何在可能的情况下使元素居中而不与侧边栏重叠?

问题描述 投票:0回答:1

这就是我想要实现的目标。左侧有一个红色侧边栏,宽度用

160px
固定。同时,如果可能的话,我想将蓝色框保留在页面中央,最大宽度为
240px

但是当没有足够的空间时,我不希望蓝色框与红色框重叠,因此蓝色框不必再居中(图3)。

当空间更小时,蓝色框应缩小以适应可用空间(图 4)。

我尝试在红色框上使用

position: absolute
,但它会导致重叠。有什么建议吗?

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  height: 100vh;
}

section {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

side {
  width: 160px;
  height: 160px;
  background-color: salmon;
  flex: 0 0 160px;
  justify-self: start;
  position: absolute;
  left: 0;
}

main {
  width: 240px;
  height: 100%;
  background-color: steelblue;
  flex: 0 1 240px;
}
<section>
  <side></side>
  <main></main>
</section>

css flexbox grid-layout
1个回答
0
投票

只需在适当的媒体查询上添加边距:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  height: 100vh;
}

section {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

side {
  width: 160px;
  height: 160px;
  background-color: salmon;
  flex: 0 0 160px;
  justify-self: start;
  position: absolute;
  left: 0;
}

main {
  width: 240px;
  height: 100%;
  background-color: steelblue;
  flex: 0 1 240px;

  @media screen and (width < 560px) {
    margin-inline: 160px auto;
  }
}
<section>
  <side></side>
  <main></main>
</section>

© www.soinside.com 2019 - 2024. All rights reserved.