我有導航的以下情形:如何對齊絕對定位的元素,以父親的父親
導航欄爲紅色,它是一個導航li
。藍色區域是導航按鈕的下拉菜單。下拉菜單絕對定位,因此對齊li
元素的左邊緣。我想要的是讓下拉菜單完全定位,但要在導航欄的左邊緣對齊(紅色容器)。
我已經試過left: 0
,由於某種原因,它不適用於我的情況。有沒有其他辦法可以讓它與.navigation-bar
對齊?
我有導航的以下情形:如何對齊絕對定位的元素,以父親的父親
導航欄爲紅色,它是一個導航li
。藍色區域是導航按鈕的下拉菜單。下拉菜單絕對定位,因此對齊li
元素的左邊緣。我想要的是讓下拉菜單完全定位,但要在導航欄的左邊緣對齊(紅色容器)。
我已經試過left: 0
,由於某種原因,它不適用於我的情況。有沒有其他辦法可以讓它與.navigation-bar
對齊?
嘗試申請保證金:0和padding:0的UL認證。
它實際上是li
上的填充和邊距,它正在移動它。
嘗試添加該你的CSS您.navigation-bar ul li
選擇:
padding: 0;
margin: 0;
最終輸出:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<style>
body,
html {
padding: 0;
margin: 0;
}
.navigation-bar {
width: 100%;
display: block;
color: white;
background-color: red;
}
.navigation-bar ul li {
display: inline-block;
list-style-type: none;
padding: 0;
margin: 0;
}
.align-me {
position: absolute;
display: block;
width: 1080px;
color: white;
background-color: blue;
}
</style>
</head>
<body>
<div class="navigation-bar">
<li>Navigation button</li>
<div class="align-me">I need to be aligned to .navigation-bar</div>
</div>
</body>
</html>
由於pedram在評論中說,你需要重新設置margin
和padding
屬性。您可以編寫ul { margin: 0; padding: 0; }
,但最佳做法(我總是使用它)是使用*
選擇器來重置所有元素的margin
和padding
。這將是更容易編寫您的標記:
* {
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
\t <head>
\t \t <title>test</title>
\t \t <style>
\t \t \t body, html {
\t \t \t \t padding: 0;
\t \t \t \t margin: 0;
\t \t \t }
\t \t \t .navigation-bar {
\t \t \t \t width: 100%;
\t \t \t \t display: block;
\t \t \t \t color: white;
\t \t \t \t background-color: red;
\t \t \t }
\t \t \t .navigation-bar ul li {
\t \t \t \t display: inline-block;
\t \t \t \t list-style-type: none;
\t \t \t }
\t \t \t .align-me {
\t \t \t \t position: absolute;
\t \t \t \t display: block;
\t \t \t \t width: 1080px;
\t \t \t \t color: white;
\t \t \t \t background-color: blue;
\t \t \t }
\t \t </style>
\t </head>
\t <body>
\t \t <div class="navigation-bar">
\t \t \t <ul>
\t \t \t \t <li>Navigation button</li>
\t \t \t \t <div class="align-me">I need to be aligned to .navigation-bar</div>
\t \t \t </ul>
\t \t </div>
\t </body>
</html>
@opportunityr,你可以使用'.navigation-bar'選擇器,或者更好地使用'*'。 –
'UL { 保證金:0; 填充:0; } @ – Pedram