Search code examples
htmlcsslayout

Invalid property value for margin-left: auto


Sorry for asking a question that probably has been asked a gazillion times, but I couldnt find an answer. I don't know why the browser gives me an Invalid property value for margin-left: 0 auto yet somehow a little bit of margin is added to the left (is this a rendering bug?). It actually works without the -left but I have no idea why.

The complete example code: http://jsfiddle.net/zw7n0h2j/5/

#wrapper {
  width:800px;
}

.figure {
    display: block;
    /* margin: 0; */
    margin-left: 0 auto;
    width: 50%; 
}

.figure img {
    width: 100%;
}

.figure figcaption { 
    width: 100%;
}
<div id="wrapper">
    <figure class="figure" >
        <img src="https://via.placeholder.com/350x150" />
        <figcaption>My caption</figcaption>
    </figure> 
</div>


Solution

  • margin-left cannot have multiple arguments. unlike margin. so margin-left: 0 auto is invalid as 0 and auto are two separate arguments, while margin: 0 auto is valid as this is shorthand for

    margin-top: 0;
    margin-bottom: 0;
    margin-left: auto;
    margin-right: auto;
    

    These are applied in a clockwise order, so if you do margin: 12px, 13px, 14px, 15px; the margins would be applied to the top, right, bottom, and left items respectfully.

    Read more about it here.