Floats and Margins

by audetwebdesign

HTML

<h3>Basic - No margins or padding - text wraps around floats.</h3>
<div class="wrap">
    <div class="one mark">one - add some text to make it taller for effect.</div>
    <div class="two mark">two - single liner</div>
    <div class="marginfix">three - Nulla vehicula libero id nulla vestibulum ullamcorper. Duis convallis ligula et enim dignissim facilisis. Nulla eleifend vulputate eros vel consectetur.</div>
</div>

<h3>Example 2 - Add left/right margins to inflow block</h3>
<div class="wrap ex2">
    <div class="one mark">one - add some text to make it taller for effect.</div>
    <div class="two mark">two - single liner</div>
    <div class="marginfix">three - Nulla vehicula libero id nulla vestibulum ullamcorper. Duis convallis ligula et enim dignissim facilisis. Nulla eleifend vulputate eros vel consectetur.</div>
</div>

<h3>Example 3 - Changing the order of the elements</h3>
<div class="wrap ex3">
    <div class="one mark">one - add some text to make it taller for effect.</div>
    <div class="marginfix">three - Nulla vehicula libero id nulla vestibulum ullamcorper. Duis convallis ligula et enim dignissim facilisis. Nulla eleifend vulputate eros vel consectetur.</div>
    <div class="two mark">two - single liner</div>
</div>

<h3>Example 4 - Changing the order of the elements &amp; left/right margins</h3>
<div class="wrap ex4">
    <div class="one mark">one - add some text to make it taller for effect.</div>
    <div class="marginfix">three - Nulla vehicula libero id nulla vestibulum ullamcorper. Duis convallis ligula et enim dignissim facilisis. Nulla eleifend vulputate eros vel consectetur.</div>
    <div class="two mark">two - single liner</div>
</div>

<h3>Example 5 - Establish a new block formatting context (no margins)</h3>
<div class="wrap ex5">
    <div class="one mark">one - add some text to make it taller for effect.</div>
    <div class="marginfix">three - Nulla vehicula libero id nulla vestibulum ullamcorper. Duis convallis ligula et enim...

CSS

.wrap {
    width: 600px;
    background-color: lightgray;
    margin: 0 auto;
    overflow: auto; /* Optional: allows background to extend to any overflowing elements */
    padding: 1px; /* Optional: keeps outlines from being hidden at the edges */
}
.one {
    width: 200px;
    float: left;
}
.two {
    width: 200px;
    float: right;
}
.wrap .mark {
     outline: 1px dashed blue;
}

.ex2 .marginfix {
    margin: 0 210px;
    outline: 1px dotted blue;
}

.ex4 .marginfix {
    margin: 0 210px;
    outline: 1px dotted blue;
}

.ex5 .marginfix {
    overflow: hidden;
    outline: 1px dotted blue;
}