Higeath Higeath - 1 year ago 77
HTML Question

Keeping absolute flex item aligned with block div

I have text and II lines and I want to keep them aligned at all times here is demo: https://jsfiddle.net/uh7ra6v5/ . There are two lines and below there is text 2016 I want them to be aligned properly and right now when resizing the window text slides slightly.

It is more clearly visible when you resize the window so the layout changes a little bit and text and lines are aligned to the right side.



.verticalLine:before {
content: "";
display: block;
position: absolute;
border-left: 0.13em solid #B9D7D9;
border-right: 0.13em solid #B9D7D9;
height: 100%;
width: 0.8rem;
margin-left: 42%;
box-sizing: border-box;
}
.verticalLine {
position: relative;
width: 10%;
flex-shrink: 0;
}
.flex {
display: flex;
}
.side {
width: 45%;
}
.year {
width: 100%;
text-align: center;
color: #B35300;
}
@media only screen and (max-width: 768px) {
header h1 {
font-size: 3rem;
}
.year {
text-align: right;
}
.side {
width: 90%;
}
}

<div class="flex rev">
<div class="side">test
<br>test
<br>test</div>
<div class="verticalLine">
</div>
</div>

<div class="year">
2016
</div>




Answer Source

Since you're already using flexbox, you can complete the layout with flex properties. There's no need for absolute positioning.

.flex {
    display: flex;
}
.side {
    flex: 0 0 45%;                      /* 1 */
}
.verticalLine {
    display: flex;                      /* 2 */
    flex-direction: column;
    align-items: center;                /* 3 */ 
    flex: 0 0 10%;                      /* 1 */
}
.verticalLine:before {
  flex: 1;                              /* 4 */
  content: "";
  border-left: 0.13em solid #B9D7D9;
  border-right: 0.13em solid #B9D7D9;
  width: 0.8rem;
  box-sizing: border-box;
  
}
.year {
  color: #B35300;
}
<div class="flex rev">
  <div class="side">test<br>test<br>test</div>
  <div class="verticalLine">
       <div class="year">2016</div>
  </div>
</div>

jsFiddle

Notes:

  1. Simplify code by combining flex-shrink and width from original code.
  2. Make lines element a nested flex container in column-direction. Both the lines (a pseudo-element) and the text (a DOM element) are child elements and can accept flex properties.
  3. Horizontally center the lines and text.
  4. Line consume all available space in the container.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download