內部DIV設定position: absolute該如何居中

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>測試</title>
<style>
.className1{
width: 300px;
height: 300px;
margin:0 auto;
background-color: red;
position: relative;
}

.className2{
position: absolute;
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<div>
<div></div>
</div>
</body>
</html>

頁面效果見圖1

圖1:css

試過在className2里加html

margin:0 auto

在有position: absolute;出現時margin:0 auto;是不起做用的測試


解決沒法居中的辦法:spa

在className2里加入如下代碼:code

left:50%;
margin-left: -100px;

效果圖:htm

如今已經解決問題。it

若是隻是單純的設置爲
io

left:50%

效果是這樣的:class

margin-left的值須要是寬度的一半;meta

相關文章
相關標籤/搜索