3

I have an HR element inside a 50%'s width div container and I would like the HR to extend to all the width of the screen ignoring it's parent width.

I know I can solve this by applying the HR outside the container and use relative position to make it move where it has to be... but is there another solution?

I tried setting the width more than 100%, lets say 300% and let it overflow, but it will only enlarge to the right (and show an ugly scrollbar).

Browser treat HR as a block but I was unable to center it with margin: 0 auto (after resizing it as above).

Is there a way to accomplish this without relative positioning?

jviotti
  • 17,881
  • 26
  • 89
  • 148
  • Try with `!important;`. See also [link](http://stackoverflow.com/questions/946645/how-to-ignore-parent-css-style). – Vucko Dec 30 '12 at 15:02
  • 1
    A child element is not supossed to ignore of the container. !important would only be usefull if I had two styles applied to the same element – jviotti Dec 30 '12 at 15:05

4 Answers4

9

You can use a negative margin for the hr like this:

hr {
  width: 200%;
  margin-left: -50%;
}​

Fiddle

Note, these %s will only extend to the end of the viewport if its parent div is at the top level and/or no other parent has width, padding, or margin attached. To handle that, maybe try a width: 9999px; margin-left: -3333px; and an overflow: hidden on the body

Scrimothy
  • 2,536
  • 14
  • 23
1

I stumbled upon this question after searching for a similar thing. Since (sadly) I didn't find a CSS-only solution for this problem, I ended up using jQuery to do the job.

function hrExpand() {
   var windowWidth = $(window).width();
   $('hr').width(windowWidth).css('margin-left', function(){
     return '-' + ($(this).offset().left) + 'px';
   });
}

Just make sure to run the function both onload and onresize.

Example: http://codepen.io/anon/pen/qEOoGb

(You could replace $('hr') with e.g. $('.content > hr') to increase performance a bit and prevent it from replacing ALL the hr's on your page)

elveti
  • 2,316
  • 4
  • 20
  • 27
0

If you use the right values, using relative positioning works without a scrollbar:

div {
    width: 50%;
    min-height: 20em;
    margin: 0 auto;
}

hr {
    width: 200%;
    position: relative;
    left: -50%;
}

If a div is 50%, and you want the hr to be 100% of the root (twice as big as 50%), use 200%. For a 25% div, use a 400% hr, etc

Demo

bookcasey
  • 39,223
  • 13
  • 77
  • 94
0

If working with tailwind:

<hr class="my-2 -ml-10 -mr-10"/> 

I have not tested bootstrap

James Ikubi
  • 2,552
  • 25
  • 18