Why doesn't margin:0 auto work?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="head">set in middle and center</div>
    <div id="main">
        <img src="image/i1.png" alt="">
    </div>
    
</body>
</html>

the following css

*{
    padding:0;
    margin:0;
    text-decoration:none;
}
-sharphead{
    width:600px;
    height:40px;
    border:1px solid red;
    margin:0 auto;
    line-height:40px;
    font-size:20px;
    text-align:center;
}

-sharpmain{
    width:600px;
    height:392px;
    border:1px solid green;
    margin:0 auto;
    text-align:center;
    vertical-align:middle;
    display:table-cell;
}

although the picture inside is centered, margin:0 auto no longer works on div-sharpmain. Why?
what did display:table-cell; do?

Mar.16,2021

  • margin:0 auto only works on block-level elements. display:table-cell is equivalent to < td > element, and does not belong to block level element
  • display:table-cell it is recommended to use
  • nested in display:table .

if you set display:table-cell;, margin will fail. You can use flexible layout to achieve the effect you want

.container {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

you did not set the height and width of the box

Menu