Make child div stretch across width of page

后端 未结 12 602
鱼传尺愫
鱼传尺愫 2020-12-13 09:24

Suppose I have the following HTML code:

相关标签:
12条回答
  • 2020-12-13 09:30

    You can do:

    margin-left: -50%;
    margin-right: -50%;
    
    0 讨论(0)
  • 2020-12-13 09:31

    Since position: absolute; and viewport width were no options in my special case, there is another quick solution to solve the problem. The only condition is, that overflow in x-direction is not necessary for your website.

    You can define negative margins for your element:

    #help_panel {
        margin-left: -9999px;
        margin-right: -9999px;
    }
    

    But since we get overflow doing this, we have to avoid overflow in x-direction globally e.g. for body:

    body {
        overflow-x: hidden;
    }
    

    You can set padding to choose the size of your content.

    Note that this solution does not bring 100% width for content, but it is helpful in cases where you need e.g. a background color which has full width with a content still depending on container.

    0 讨论(0)
  • 2020-12-13 09:32

    You could do it with jQuery...

    $("#help_panel").width($(window).width());
    

    Otherwise, as far as css goes, I'm fairly sure you would have to sit the help_panel div on the outside of container using position:absolute styling: http://css-tricks.com/forums/discussion/2318/give-child-div-width%3A100-of-page-width-inside-parent./p1

    0 讨论(0)
  • 2020-12-13 09:33

    You can use 100vw (viewport width). 100vw means 100% of the viewport. vw is supported by all major browsers, including IE9+.

    <div id="container" style="width: 960px">
       <div id="help_panel" style="width: 100vw; margin: 0 auto;">
         Content goes here.
       </div> 
    </div>
    
    0 讨论(0)
  • 2020-12-13 09:36

    With current browsers (this question is dating a bit now), you can use the much simpler vw (viewport width) unit:

    #help_panel {
      margin-left: calc(50% - 50vw);
      width: 100vw;
    }
    

    (usage data: http://caniuse.com/#feat=viewport-units)

    From my tests, this should not break your flow while being easy to use.

    0 讨论(0)
  • 2020-12-13 09:38

    Yes it can be done. You need to use

    position:absolute;
    left:0;
    right:0;
    

    Check working example at http://jsfiddle.net/bJbgJ/3/

    0 讨论(0)
提交回复
热议问题