HTML CSS将div的中间水平对齐到另一个div侧

时间:2016-06-29 18:33:36

标签: html css3 alignment

我正在努力实现以下结果:
  在水平方向上,div 2的中间与div 1的右侧对齐

_______________________________________
| div 1 _________ | _______
| | div 2 | |
| | | |
| | _________ | _______ |
| ______________________________________ |


div的宽度将根据其他约束设置,但无论大小如何,我都希望它们保持这种配置。

我想要一个纯CSS3解决方案(没有javascript调整大小......)

请注意,此问题与垂直对齐无关。

如果您有解决方案,请与我们联系。

谢谢。

3 个答案:

答案 0 :(得分:1)

使用'position'属性是一个选项。 我不确定这是否可以解决您的问题:

Example

div{
    height:400px;
    width:400px;
    background:blue;
    position:relative;
}

div div{
    width:50%;
    height:50%;
    background:skyblue;
    position:absolute;
    left: 100%;
    top: 50%;
    transform: translate(-50%, -50%);
    -webkit-transform: translate(-50%, -50%);
}

答案 1 :(得分:1)

设置为transform: translate时,您可以使用left: 100% CSS将内部元素移动到正确的位置:

html, body { width: 100%; height: 100% }
div { position: relative; border: 2px solid #f00; overflow: visible; }
#div1 { width: 50%; height: 33%; }
#div2 { width: 50%; height: 50%; border-color: #0f0; }
#div2 { position: absolute; left: 100%; top: 50%; transform: translate(-50%,-50%) }
You could use the `transform: translate` to position the inner element when setting the position of the element at `left: 100%`.
<div id="div1">
  <div id="div2"></div>
</div>

答案 2 :(得分:0)

使div 2成为div 1的子元素,使用绝对定位并在css中使用calc()作为值。

.div1 {
  position: relative;
  border: 1px dashed black;
  width:150px;
  height:50px;
}
.div2 {
  position: absolute;
  right:calc(-50% + 25px);
  top: calc(100% - 75%);
  border: 1px dashed green;
  width:100px;
  height:50%;
}

Here's a jsfiddle