Search code examples
htmlcsscss-position

How to place a <hr> relatively to a parent <div>?


I would like to use a <hr> as an indicator of progress within a <div>. To this I expected that a combination of position: absolute and top: ...px would do the job:

.container {
  border-style: solid;
  border-color: red;
  width: 300px;
  height: 300px;
}

.box {
  border-style: solid;
  border-color: blue;
  width: 200px;
  height: 200px;
}

hr {
  margin: 0;
  position: absolute;
  top: 150px;
}
<div class="container">
  <div class="box">
    <hr class="line">
  </div>
</div>

I was expecting the line to be 3/4 down from the top of the blue box:

enter image description here

Why is my positioning wrong?


EDIT: Through trial-and-error, I discovered that by adding a width: 200px; to the hr definition I can see the line, but I do not understand why so I am not making an answer of it. Specifically: what happens that the HR does not fill the width of the container on its own anymore

.container {
  border-style: solid;
  border-color: red;
  width: 300px;
  height: 300px;
}

.box {
  border-style: solid;
  border-color: blue;
  width: 200px;
  height: 200px;
}

hr {
  margin: 0;
  position: absolute;
  top: 150px;
  width: 200px;
}
<div class="container">
  <div class="box">
    <hr class="line">
  </div>
</div>


Solution

  • The width property makes an element behave as if it was display: block in terms of space and position. Even if it was display: inline to begin with (like <a> or <span>). As for the hr element - it seems to have 0 width when it has absolute positioning. Reason: any absolute element is shrink-to-fit and hr has no content - thanks to Temani Afif's comment.

    Another issue you will have, the container needs to be position: relative for the absolute positioning within it to be correct. That has a nice side effect that a percent of width will be of the width of the containing div. Perfect for progress bars.

    .container {
      border-style: solid;
      border-color: red;
      width: 300px;
      height: 300px;
    }
    
    .box {
      border-style: solid;
      border-color: blue;
      position: relative;
      width: 200px;
      height: 200px;
    }
    
    .line {
      margin: 0;
      position: absolute;
      top: 150px;
      width: 100%;
    }
    <div class="container">
      <div class="box">
        <hr class="line">
      </div>
    </div>