简体   繁体   中英

Extend HR width to all screen ignoring container's width

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?

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; width: 9999px; margin-left: -3333px; and an overflow: hidden on the body

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 eg $('.content > hr') to increase performance a bit and prevent it from replacing ALL the hr's on your page)

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

If working with tailwind:

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

I have not tested bootstrap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM