简体   繁体   English

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

[英]HTML CSS horizontally align the middle of a div to another div side

I'm trying to achieve the following result: 我正在尝试实现以下结果:
horizontally, the middle of div 2 is aligned with the right side of div 1 在水平方向上,div 2的中间与div 1的右侧对齐

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


the width of the divs will be set based on other constraints, but, regardless of their sizes, I would like them to stay in this configuration. div的宽度将基于其他约束条件进行设置,但是无论它们的大小如何,我希望它们保持这种配置。

I would like a pure CSS3 solution (no javascript resizing...) 我想要一个纯CSS3解决方案(无需调整JavaScript大小...)

Please note that this question is NOT about vertical alignment. 请注意,此问题与垂直对齐无关。

Please let me know if you have a solution. 如果您有解决方案,请告诉我。

Thank you. 谢谢。

With 'position' property is an option. 使用“ position”属性是一种选择。 I'm not sure if this can be a possible solution to your problem: 我不确定这是否可以解决您的问题:

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%);
}

You could use the transform: translate CSS to move the inner element to the correct position when set to left: 100% : 您可以使用以下transform: translate CSS设置为left: 100%时,将CSS内部元素移动到正确的位置left: 100%

 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> 

Make div 2 a child of div 1, use absolute positioning and use calc() in your css for the values. 将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 这是一个jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM