2017-10-07 96 views
0

我有导航的以下情形:如何对齐绝对定位的元素,以父亲的父亲

导航栏为红色,它是一个导航li。蓝色区域是导航按钮的下拉菜单。下拉菜单绝对定位,因此对齐li元素的左边缘。我想要的是让下拉菜单完全定位,但要在导航栏的左边缘对齐(红色容器)。

我已经试过left: 0,由于某种原因,它不适用于我的情况。有没有其他办法可以让它与.navigation-bar对齐?

什么它看起来像现在 enter image description here

它所需要的样子 enter image description here

+3

'UL { 保证金:0; 填充:0; } @ – Pedram

回答

0

尝试申请保证金:0和padding:0的UL认证。

0

它实际上是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>

0

由于pedram在评论中说,你需要重新设置marginpadding属性。您可以编写ul { margin: 0; padding: 0; },但最佳做法(我总是使用它)是使用*选择器来重置所有元素的marginpadding。这将是更容易编写您的标记:

* { 
 
    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>

+0

@opportunityr,你可以使用'.navigation-bar'选择器,或者更好地使用'*'。 –

相关问题