Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a "container" div to which I gave margin:auto;.

It worked fine as long as I gave it a specific width, but now I changed it to inline-block and margin:auto; stopped working

Old code (works)

#container {
    border: 1px solid black;
    height: 200px;
    width: 200px;
}
.MtopBig {
    margin-top: 75px;
}
.center {
    margin-left: auto;
    margin-right: auto;
    text-align: center;
}
<div class="center MtopBig" id="container"></div>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
475 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is no longer centered because it now flows on the page in the same way inline elements do (very similarly to img elements). You will have to text-align: center the containing element to center the inline-block div.

#container {
    border: 1px solid black;
    display: inline-block;
    padding: 50px;
}
.MtopBig {
    margin: 75px auto;
    position: relative;
}
.center {
    text-align: center;
}
<div class="center">
    <div class="MtopBig" id="container"></div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...