網格以行和列佈局的形式排列內容。 CSS網格也是如此。
將網格項目設定為彈性容器−
display: flex
要垂直和水平居中,使用−
align-items: center; justify-content: center;
讓我們來看一個完整的例子 −
<!DOCTYPE html> <html> <head> <title>Grid and Flex Example</title> <style> html,body { margin: 0; padding: 0; } .box { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 100vh; } .first, .second { display: flex; align-items: center; justify-content: center; } .first { background-color: orange; } .second { background-color: yellow; } </style> </head> <body> <div class="box"> <div class="first">Left</div> <div class="second">Right</div> </div> </body> </html>
我們也可以不使用Flex來居中。我們將網格容器設定為display: grid。當display屬性設定為grid時,HTML元素將成為網格容器 -
grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 150px; grid-gap: 20px; }
網格專案使用相對定位設定 -
grid-item { position: relative; text-align: center; }
然而,
<!DOCTYPE html> <html> <head> <title>Grid</title> <style> grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: 150px; grid-gap: 20px; } grid-item { position: relative; text-align: center; } grid-container { background-color: red; padding: 10px; } grid-item { background-color: orange; } </style> </head> <body> <grid-container> <grid-item>This is in the center</grid-item> <grid-item>This is in the center</grid-item> </grid-container> </body> </html>
以上是如何在CSS Grid中居中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!