user2212238
user2212238

Reputation: 11

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 1                                                   _________|_______
|                                                          |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.

I would like a pure CSS3 solution (no javascript resizing...)

Please note that this question is NOT about vertical alignment.

Please let me know if you have a solution.

Thank you.

Upvotes: 0

Views: 51

Answers (3)

BillyNate
BillyNate

Reputation: 908

You could use the transform: translate CSS to move the inner element to the correct position when set to 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>

Upvotes: 1

Joram Clervius
Joram Clervius

Reputation: 179

Make div 2 a child of div 1, use absolute positioning and use calc() in your css for the values.

.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

Upvotes: 0

Marta Gonz&#225;lez
Marta Gonz&#225;lez

Reputation: 44

With 'position' property is an option. 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%);
}

Upvotes: 1

Related Questions