mike yaworski mike yaworski - 5 months ago 18
CSS Question

Add Horizontal Lines Between Elements

I'm trying to add a horizontal line between two elements, like LinkedIn:
enter image description here
I can't get the line on the left of the image to stop at the left side count. I've been Googling for a long time and can't find this particular case. I'm sure it's out there, but I haven't found it. This is how far I've gotten:

The HTML:

<label>count</label>
<div class="img">
<img src="http://i.stack.imgur.com/qh235.png" />
</div>


And the CSS:

div.img {
position: relative;
font-size: 30px;
z-index: 1;
overflow: hidden;
text-align: right;
}
div.img:before {
position: absolute;
top: 51%;
overflow: hidden;
width: 100%;
margin-left: -100%;
text-align: right;
height: 1px;
content: '\a0';
background-color: blue;
}


http://jsfiddle.net/XWVxk/1465/

enter image description here
I also thought that this structure might be an option (div in between elements with the div having a border):

The HTML:

<label>count</label>
<div class="hr-line"></div>
<img src="http://i.stack.imgur.com/qh235.png" />


And the CSS:

div.hr-line {
position: relative;
display: inline-block;
margin-left: 5px;
margin-right: 5px;
width: 100%;
border-bottom: 1px solid #7A7A7A;
}


http://jsfiddle.net/XWVxk/1464/

But it doesn't work exactly either. If anyone could touch up either attempt, it would be great.

Answer

If you can use flex-box, it's really easy.

p.divider {
  display: flex;
  flex-direction: row;
  align-items: center;
}
p.divider * {
  flex-shrink: 0
}
p.divider span.divider {
  width: 100%;
  flex-shrink: 1;
  border-bottom: 1px solid black;
  margin: 5px
}
<p class="divider">
  <span>Part1</span>
  <span class="divider"></span>
  <span>part2</span>
</p>

Here's the logic:

explanation of solution

span.divider is set to fill 100% of the width, but because this is a flex-box layout, the line cannot overflow (unless specified). When we tell the layout that none of the elements can shrink:

p.divider * {
  flex-shrink: 0
}

Then set span.divider as the only element that can shrink, it will shrink to fit all of the other elements on the line.


If you cannot use flex, you still can achieve the effect.

p.divider {
  background: linear-gradient(transparent 45%, black 45%, black 55%, transparent 55%);
  overflow: hidden;
}
p.divider > * {
  background: white;
  padding: 0 5px;
}
p.divider > .right {
  float: right;
}
<p class="divider">
  <span>Hola!!</span>
  <span class="right">Hola2!!</span>
</p>

Explanation:

explanation

You are setting p.divider's background to a linear-gradient of the color you want, then covering settings it's children to a solid color to hide it where there is content. (You can also use an image for the background)

What are the drawbacks of this? If you have a background image behind it, it looks bad:

problem with float

As opposed to the flex layout:

flex-layout on image