简体   繁体   English

无法使用保证金自动将导航栏居中

[英]Can't centre my nav bar with margin auto

I am having trouble centring my nav bar using margin: auto in my responsive design. 我在使用自适应设计的margin:auto时无法将导航栏居中。 Seems so simple, but for some reason is not working. 似乎很简单,但是由于某种原因无法正常工作。

Here is my CSS and HTML for the nav portion of my page. 这是页面导航部分的CSS和HTML。 What I want to do is always have the nav bar centred, no matter whether a device is in landscape or portrait orientation. 我想做的就是始终将导航栏居中,无论设备是横向还是纵向。 Right now it just stays stuck to the left. 现在,它只是停留在左侧。 Any advice would be greatly appreciated. 任何建议将不胜感激。

#navwrapper{
width:100%; 
}

#navdiv{
width: 290px;
margin: 0 auto;
padding:0;
clear:both;
}

/*navigation boxes*/
#home{
height:32px;
width:55px;
background-color:#1d5a61;
padding: 18px 0 0 0;
margin: 0 5px;;
float:left;
}


#products{
height: 43px;
width: 75px;
background-color:#789949;
padding: 7px 0 0 0;
margin: 0 5px;
float: left;
}


#know{
height: 38px;
width: 60px;
background-color:#1d5a61;   
padding:12px 0 0 0;
margin: 0 5px;
float: left;
}


#contact{
height: 38px;
width: 55px;
background-color:#789949;
padding:12px 0 0 0;
margin: 0 5px;
float:left;
}

<div id="navwrapper">
<div id="navdiv">
<div id="home">
<h3><a href="index.html">Home</a></h3>
</div>
<div id="products">
<h3><a href="products.html">Products<br />
&amp;<br />
Services</a></h3>
 </div>
<div id="know">
<h3><a href="did_you_know.html">Did You Know?</a></h3>
</div>
<div id="contact">
<h3><a href="contact.html">Contact<br />
Us</a></h3>
</div>
</div>
</div>

I believe when centering an element that has child elements floating it will not work. 我相信,在将具有浮动子元素的元素居中时,它将无法工作。 I recommend replacing the float:left on each element of the navdiv with display: inline-block 我建议用display:inline-block替换navdiv的每个元素上的float:left

#navwrapper{
width:100%; 
}

#navdiv{
width: 290px;
margin: 0 auto;
padding:0;
clear:both;
}

/*navigation boxes*/
#home{
height:32px;
width:55px;
background-color:#1d5a61;
padding: 18px 0 0 0;
margin: 0 5px;;
**display: inline-block;**
}


#products{
height: 43px;
width: 75px;
background-color:#789949;
padding: 7px 0 0 0;
margin: 0 5px;
**display: inline-block;**
}


#know{
height: 38px;
width: 60px;
background-color:#1d5a61;   
padding:12px 0 0 0;
margin: 0 5px;
**display: inline-block;**
}


#contact{
height: 38px;
width: 55px;
background-color:#789949;
padding:12px 0 0 0;
margin: 0 5px;
**display: inline-block;**
}

I have entered your code into blank project and your navbar seems centered. 我已经将您的代码输入到空白项目中,并且您的导航栏似乎居中。 Here's a screenshot . 是截图

Maybe, the problem is elsewhere. 也许问题出在其他地方。 Can you provide a link to whole file see? 您可以提供指向整个文件的链接吗? :) :)

Margin:0 auto sometimes does not work for few doctypes. Margin:0 auto有时不适用于少数文档类型。 You could check or change the doctype to rule out this issue and try. 您可以检查或更改文档类型以排除此问题,然后尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM