Home > Back-end >  CSS: Cannot horizontally center by using margin
CSS: Cannot horizontally center by using margin

Time:12-19

I have tried to using margin: 0 auto; to horizontally center the div elements however I don't understand why the items are always appearing on the left of the HTML page.

body {
    background: #f06d06;
    font-size: 80%;
}

main {
     display: inline-block;
     background: white;
     line-height: 300px;
     height: 300px;
     margin: 20px auto;
     width: 300px;
     resize: vertical;
     overflow: auto;
     vertical-align: middle;
}

div {
        display: inline-block;
        vertical-align: middle;
        height: 100px;
        line-height: 100px;
        background-color: black;
        padding: 50px;
        margin: 0 auto;
}

p {
        display: inline-block;
        vertical-align: middle;
        color: white;
        margin: 0;
        line-height: 1.5;    
}
<body> 
    <main>
        <div>
            <p>center align</p>
        </div>
    </main>
</body>

Could anyone tell me what I am doing wrong?

CodePudding user response:

set text-align:center to main.

main{
display: inline-block;
background: white;
line-height: 300px;
height: 300px;
width: 300px;
resize: vertical;
overflow: auto;
vertical-align: middle;
text-align:center;
}

CodePudding user response:

Try This, I Changed div display properties

body {
    background: #f06d06;
    font-size: 80%;
}

main {
     display: inline-block;
     background: white;
     line-height: 300px;
     height: 300px;
     margin: 20px auto;
     width: 300px;
     resize: vertical;
     overflow: auto;
     vertical-align: middle;
}

div {
        display: block;
        vertical-align: middle;
        height: 100px;
        width: 100px;
        line-height: 100px;
        background-color: black;
        padding: 50px;
        margin: 0 auto;
}

p {
        display: inline-block;
        vertical-align: middle;
        color: white;
        margin: 0;
        line-height: 1.5;    
}
<body> 
    <main>
        <div>
            <p>center align</p>
        </div>
    </main>
</body>

  • Related