CSS實(shí)現(xiàn)高寬相等:
// method 1: CSS表格布局實(shí)現(xiàn) .container { display: table; width: 100%; height: 100%; } .item { display: table-cell; vertical-align: middle; text-align: center; } // method 2: Flex布局實(shí)現(xiàn) .container { display: flex; justify-content: center; align-items: center; } .item { flex: 1; width: 100%; height: 100%; text-align: center; } // method 3: 絕對(duì)定位布局實(shí)現(xiàn) .container { position: relative; width: 100%; height: 100%; } .item { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 80%; height: 80%; text-align: center; } // method 4: Grid布局實(shí)現(xiàn) .container { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-auto-rows: minmax(200px, auto); grid-gap: 10px; } .item { width: 100%; height: 100%; text-align: center; }
以上是常用的幾種方法,具體選擇方法需要根據(jù)實(shí)際場(chǎng)景做出判斷。總體來(lái)說(shuō)CSS表格布局和Flex布局比較常用,實(shí)現(xiàn)起來(lái)比較簡(jiǎn)單明了。如果有需要可以嘗試使用其他方法,比如Grid布局。