Negative margin with float for two-column layout

2019-07-23 22:27发布

问题:

I saw two column layout made as following way, but I didn't understand why it works. So what actually does the .col-sub do? If I remove margin-left:-100% in .col-sub, the Sub Content will fall down. If I remove float: left in it, the Sub Content can't show. What does margin-left and float do here?

Demo can also be found here: http://jsfiddle.net/yougen/ATNh9/

HTML:

<div class="wrapper">
        <div class="col-main">Main Content</div>
        <div class="col-sub">Sub Content</div>
</div>

CSS:

       * {
            padding:0;
            margin: 0;
        }

       .wrapper {
           margin: 0px auto;
           width: 960px;
           text-align: center;
           line-height: 580px;
       }

       .col-main {
           width:100%;
           height:580px;
           float: left;
           background-color: #f16529;
           border: solid 1px #000;
       }

       .col-sub {
           float: left;
           margin-left: -100%;/** -960px **/
           width: 350px;
           height: 580px;
           background-color: #f0dddd;
       }

回答1:

Use your browser’s developer tools, and play around with the margin-left value of the sub content – decrease (or rather increase?) it slowly from -100% to 0%, and you will see it move across the orange main content, then end up under it.

Under it is where it normally would go (without negative margin), because it is floated left, but it’s position in the DOM is after the main content. It would go right next to the also left-floated main content, if there was any space – but there isn’t any, because the main content is 100% wide.

By introducing a negative margin, that space is “created”. The negative margin “overwrites” the right edge of the element before the sub content, making the whole thing act as if that right edge was further to the left. When the right margin reaches -100%, it is as if the whole main element “wasn’t there” from the point of view of the left sub content – so it happily takes it’s place above the main content to the left of the wrapper element.