根据具有绝对位置的另一个来定位div

时间:2017-10-17 14:01:01

标签: css css3 flexbox

我有this fiddle.

在小提琴中,我想将绿色盒子放在大盒子的中央。另外,我想将绿色框后面的红色框放在水平线like in this fiddle上(但我不想指定像素的边距,我希望红色框的位置依赖于绿色盒子之一。)

#parent {
  width: 500px;
  height: 500px;
  background-color: white;
  border: 2px solid blue;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

#div1 {
  position: absolute;
  background: green;
  width: 30%;
  height: 30%;
  align-self: center
}

#div2 {
  margin-left: 300px;
  background: red;
  width: 30%;
  height: 30%;
  align-self: center
}

*/
<div id="parent">
  <div id="div1"></div>
  <div id="div2"></div>
</div>

绿框的位置是给定的(我无法更改position:absolute)。如何在它之后立即放置红色框?

2 个答案:

答案 0 :(得分:2)

使用a pseudo element匹配红色 + 绿色项目的总宽度。

需要添加的left/right/transform属性来将绝对定位的绿色元素置于跨浏览器中心。

Stack snippet

&#13;
&#13;
#parent {
  width: 500px;
  height: 500px;
  background-color: white;
  border: 2px solid blue;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

#parent::before {
  content: '';
  width: 60%;                           /*  sum of green and red  */
  height: 60%;                          /*  sum of green and red  */
}

#div1 {
  background: green;
  width: 30%;
  height: 30%;
  position: absolute;
  left: 50%;                            /*  added  */
  top: 50%;                             /*  added  */
  transform: translate(-50%,-50%);      /*  added  */
}

#div2 {
  background: red;
  width: 30%;
  height: 30%;
}
&#13;
<div id="parent">
  <div id="div1"></div>
  <div id="div2"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你的意思是这样的吗?:

https://jsfiddle.net/5xkezz1z/5/

<强> HTML:

<div id="parent">
  <div id="div1"></div>
  <div id="div2"></div>
</div>

<强> CSS:

#parent {
    width:500px;
    height:500px;
    background-color:white;
    border:2px solid blue;
    position:relative;
    display: flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
}
#parent div{
  flex: 0 0 33%;
  width: 35%;
}
#div1 {background:green}
#div2 {background:red}

或类似的东西?:

https://jsfiddle.net/5xkezz1z/6/

<强> HTML:

<div id="parent">
    <div class="blocks">
        <div id="div1"></div>
        <div id="div2"></div>
     </div>
</div>

<强> CSS:

#parent {
    width:500px;
    height:500px;
    background-color:white;
    border:2px solid blue;
    position:relative;
    display: flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
}
#parent .blocks{
    width: 40%;
    height: 50%;
    display: flex;
}
#parent .blocks div{
    width: 100%;
    height: 100%;
}
#div1 {background:green}
#div2 {background:red}