如何用 CSS将 div水平地置于其父 div内?
CSS
div
<div id='parent' style='width: 100%;'> <div id='child' style='width: 50px; height: 100px;'>Text</div> </div>
<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>
I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.
div#child { margin: 0 auto; }
<div id='parent' style='width: 100%;text-align:center;'> <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div> </div>
您可以使用左右边距的“ auto”值,让浏览器在内部 div 的两边平均分配可用空间:
<div id='parent' style='width: 100%;'> <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div> </div>
只是出于兴趣,如果你想要居中两个或更多的 div (所以他们并排在中心) ,然后这里是如何做到这一点:
<div style="text-align:center;"> <div style="border:1px solid #000; display:inline-block;">Div 1</div> <div style="border:1px solid red; display:inline-block;">Div 2</div> </div>
.parent-container { display: flex; justify-content: center; align-items: center; } .child-canvas { flex-shrink: 0; }