【问题标题】:Two div equally spaced form center above another div两个 div 等距形成中心在另一个 div 上方
【发布时间】:2023-03-20 17:35:01
【问题描述】:

我需要两个 div,其图像与页面中心等距,一个在左侧,另一个在右侧,位于中心 div 上方。

我试着在下图中做了一个例子:

主页div(花朵)为1024像素,左右两个蓝色div需要保持在同一位置... 我不是那个 CSS 专家……我怎样才能实现这种行为?

到目前为止我的 CSS 代码:

.overlay-left{
background-color: transparent !important;
 background-image: url("/images/background-left.png");
 background-position: center top;
  background-repeat: no-repeat;
   height: 100vw;
position: absolute;
    width: 400px;
    //left: calc(-60vw + 50%);
    left: calc(-50% + 600px);
margin-left: -150px;
  z-index: 100;
}


.overlay-right{
background-color: transparent !important;
 background-image: url("/images/background-right.png");
 background-position: center top;
  background-repeat: no-repeat;
   height: 100vw;
position: absolute;
    width: 400px;
    //left: calc(+130vw - 50%);
    left: 1024px;
margin-left: 100px;
  z-index: 100;
}

【问题讨论】:

  • 希望您至少尝试自己编写代码。 Stack Overflow 不是代码编写服务。我建议您通过 Google 或通过搜索 SO 进行一些额外的研究,然后尝试一下。如果您仍然遇到问题,请返回您的代码并解释您尝试过的方法以及为什么它不起作用。
  • 好的,我会发布我的代码
  • 您希望将 div(左右)从左右设置为 0 还是稍微多一点?
  • 我为主体使用了 1024 px 的固定宽度。左右 div 是宽度为 400 像素的图像......理想情况下,它们需要以 0(因此,从 -200 到 +200)像素和 1024 像素(因此,从 +800 到 + 1224 像素)为中心,如我发布的模型......
  • 我在摆弄:left: calc(50vw -800px); (应该是视口宽度的一半 - 800 像素......)但不起作用......

标签: html css web


【解决方案1】:

您需要为您的图片定义一个父级(此处为#parent,然后将图片和另外两个 div[s] 放入该父级中。

您可以这样做:

#parent{
 position:relative;
  
  }

#parent img{
max-width:94%;
  display:block;
  margin:auto;
  
}

#parent> div{
width:50px;
  height:300px;
  background:rgba(125,125,255,0.5);
  position:absolute;
  top:0;
  bottom:0;
  margin:auto;
 
}
#right{
 right:0; 
}

#left{
left:0;
}
<div id="parent">
  <img src="http://www.planwallpaper.com/static/images/744081-background-wallpaper.jpg"/>  
  <div id="right"></div>
  <div id="left"></div>
</div>

【讨论】:

    【解决方案2】:

    我想我通过使用 Calc 解决了这个问题。 我需要计算页面宽度的一半,然后减去或添加固定数量的像素。 我在没有运气的情况下使用 Left 和 Calc,直到我发现:

    How to set the 'left' property of my div using css3 calc?

    所以基本上我需要使用 webkit-calc、moz-cal 而不是简单的“calc”

    现在这是一个工作 CSS 的 sn-p:

    .overlay-left{
    background-color: transparent !important;
    background-image: url("/images/background-left.png");
    background-position: center top;
    background-repeat: no-repeat;
    height: 100vw;
    position: absolute;
    width: 400px;
    left:-webkit-calc(100%/2 - 842px);
    left:-moz-calc(100%/2 - 842px);
    left:calc(100%/2 - 842px);
    z-index: 100;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多