CSS: Can a div “float:middle” rather than “float:left;” with margin-left?

You can do this in some new browsers with the flexbox model: jsFiddle

HTML

<div>
    <div>left div</div>
    <div>middle div</div>
    <div>right div</div>
</div>

CSS

body {
    width: 100%;
    height: 50px;
    display: -webkit-box;
    /* iOS 6-, Safari 3.1-6 */
    display: -moz-box;
    /* Firefox 19- */
    display: -ms-flexbox;
    /* IE 10 */
    display: -webkit-flex;
    /* Chrome */
    display: flex;
    /* Opera 12.1, Firefox 20+ */
    /* iOS 6-, Safari 3.1-6 */
    -webkit-box-orient: horizontal;
    -webkit-box-pack: justify;
    /* Firefox 19- */
    -moz-flex-direction: row;
    -moz-justify-content: space-between;
    /* Chrome */
    -webkit-flex-direction: row;
    -webkit-justify-content: space-between;
    /* IE10 */
    -ms-flex-direction: row;
    -ms-justify-content: space-between;
    /* Opera 12.1, Firefox 20+ */
    flex-direction: row;
    justify-content: space-between;
}
div {
    width: 25%;
    background-color: #EFEFEF;
}

The variously prefixed display: flex; property tells the browser that the div should use the flexbox model to layout the contents inside itself.

The variously prefixed forms of flex-direction: row; and justify-content: space-between; tell the browser to lay out the div‘s inside the div with display: flex; set as a row with the space between them equally split.

As mentioned in the comments, the above is not really cross-browser friendly, as the new flexbox model is not yet properly supported in all browsers. If you need IE8+ support, you could use the code below instead, which should work in all browsers and IE8+. jsFiddle

HTML

<div>left div</div>
<div class="middle">
    <div class="inthemiddle">middle div</div>
</div>
<div>right div</div>

CSS

html {
    display: table;
    width: 100%;
}
body {
    display: table-row;
    width: 100%;
}
div {
    display: table-cell;
    background-color: #EFEFEF;
    min-width: 200px;
}
div.middle {
    width: 100%;
    background-color: #FFF;
    text-align: center;
}
div.inthemiddle {
    text-align: left;
    display: inline-block;
    margin: 0px auto;
}

Leave a Comment