如何讓“position:absolute”元素居中?
我們可以在 Python 中輕而易舉地以水平垂直方向對絕對位置元素進行居中。為此,請使用以下 CSS 屬性。
對於水平居中,使用以下屬性 -
- 左
- 邊距左
對於垂直居中,使用以下屬性:-
- 頂部
- 邊距頂部
絕對位置元素的水平居中
示例
要水平居中絕對位置元素,請使用以下程式碼 -
<!DOCTYPE html> <html> <head> <style> div.center{ width:200px; height: 50px; left:50%; margin-left:-100px; position:absolute; background: yellow; text-align: center; } </style> </head> <body> <h1>Positioning an Element</h1> <div class='center'> This is centered horizontaly </div> </body> </html>
輸出

絕對位置元素的垂直居中
示例
要垂直居中絕對位置元素,請使用以下程式碼 -
<!DOCTYPE html> <html> <head> <style> body,html{ min-height:100%; } div.center{ width:200px; height: 50px; top:80%; margin-top:-100px; position:absolute; background: yellow; text-align: center; } </style> </head> <body> <h1>Positioning an Element</h1> <div class='center'> This is centered vertically </div> </body> </html>
輸出

絕對位置元素的水平和垂直居中
示例
要水平和垂直居中絕對位置元素,請使用以下程式碼 -
<!DOCTYPE html> <html> <head> <style> body,html{ min-height:100%; } div.center{ width:200px; height: 50px; left:50%; top:50%; margin-left:-100px; margin-top:-25px; position:absolute; background: yellow; text-align: center; } </style> </head> <body> <h1>Positioning an Element</h1> <div class='center'> This is centered vertically and horizontally </div> </body> </html>
輸出

廣告