CSS Horizontal Menu Not Centered Position Fixed

时间:2017-04-10 03:28:27

标签: html css

I was making a simple vertical menu and it worked fine. I could resize the browser, and the text would stay centered. Here's the code:

/*CSS Reset*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;

}

nav a {
    text-decoration: none;
    color: red;
    background-color: green;
    display: inline;
    font-size: 2em;
    border: black 1px solid;
    border-radius: .2em;
    padding: .01em;

}

nav li {
    display: inline;
    padding: .5em;

}

nav ul {
     background-color: green;
     text-align: center;
     vertical-align: center;

}

a:hover {
    color: black;
    background-color: grey;
    border: none;
}

Here's what it looked like. I know it's not pretty but I just started learning CSS. Anyway, I wanted the bar to stay there as you scrolled up and down so I added position: fixed; to the ul. This is what happened. I know that I have to set a width, but then the text will not stay centered when the browser is resized. Please help!

1 个答案:

答案 0 :(得分:1)

您还需要添加width(例如width: 100%),或者您可以使用left: 0; right: 0;将菜单拉伸到窗口的宽度。



/*CSS Reset*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;

}

nav a {
  text-decoration: none;
  color: red;
  background-color: green;
  display: inline;
  font-size: 2em;
  border: black 1px solid;
  border-radius: .2em;
  padding: .01em;
}

nav li {
  display: inline;
  padding: .5em;
}

nav ul {
  background-color: green;
  text-align: center;
  vertical-align: center;
  position: fixed;
  left: 0;
  right: 0;
}

a:hover {
  color: black;
  background-color: grey;
  border: none;
}

<nav>
  <ul>
    <li><a href="#">asdf</a></li>
    <li><a href="#">asdf</a></li>
    <li><a href="#">asdf</a></li>
  </ul>
</nav>
&#13;
&#13;
&#13;