我創建了一個迷宮,我想集中一個div 雖然我居中它與邊距:0自動;它不會工作Center Div內主Div
(這個div顯示,當用戶輸入牆而失去悲傷的臉上興高采烈)
#highlight_lose {
width: 550px;
height:550px;
position: absolute;
display: none;
margin: 0 auto;
}
這裏是小提琴鏈接:
我創建了一個迷宮,我想集中一個div 雖然我居中它與邊距:0自動;它不會工作Center Div內主Div
(這個div顯示,當用戶輸入牆而失去悲傷的臉上興高采烈)
#highlight_lose {
width: 550px;
height:550px;
position: absolute;
display: none;
margin: 0 auto;
}
這裏是小提琴鏈接:
如果你要使用絕對定位,你需要這樣做:
#highlight_lose {
width: 550px;
height:550px;
position: absolute;
top: 50%;
left: 50%;
margin: -225px 0 0 -225px;
display: none;
}
編輯:您還需要將position:relative;
添加到主格。這是一個更新的小提琴。
看起來了,因爲你有一個不完全居中的其他元素。
編輯:正如我前面所述,笑臉沒有看起來居中,因爲你的代碼是關閉的。迷宮真的應該在一個div裏面。然而,我只是通過玩邊際就能夠看到它的中心。
要做到這一點,你需要設置你的CSS這樣的:
#main {
position: relative;
width: 550px;
height: 550px;
float: left;
margin-left: 220px;
margin-top: 100px;
background: grey;
overflow: hidden;
}
#highlight_win {
width: 550px;
height: 550px;
position: absolute;
top: 50%;
left: 50%;
display: none;
margin: -180px 0 0 -180px;
}
#highlight_lose {
width: 550px;
height:550px;
position: absolute;
top: 50%;
left: 50%;
margin: -180px 0 0 -180px;
display: none;
}
您還需要將父div設置爲position:relative; – aaronmallen
@JoshC感謝你的時間,但它不是集中在小提琴的例子中你給我 – alonblack
@alonblack看我的編輯 – aaronmallen
.outer {
height: 600px;
width: 500px;
background-color: black;
}
.inner {
height: 200px;
width: 200px;
margin: auto;
position: relative;
top: 200px;
background-color: red;
}
標記
<div class="outer">
<div class="inner">
</div>
</div>
的想法是爲固定大小的塊元素,設置
margin:auto;
個
修復水平居中
垂直對齊中央孩子的top = half the height of the parent - half the height of the child
你的意思是垂直居中? –
當我有絕對的位置時,我有時會用這個技巧來居中。將其設置爲左側:50%;你可以設置margin-left:-275px;抵消笑臉寬度的一半。這將永遠保持你的笑臉中心。 :) – bradcush
它看起來像是在'#main'中居中。這是你想要的嗎? – DFord