导航离开屏幕但按钮没有

时间:2014-03-11 17:42:59

标签: html css

HTML:

<html>
    <head>
        <title>Parallax</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <nav>
            <br><br>
        </nav>
        <h2>One ring to rule them all</h2>
        <button>View Our Work</button>
    </body>
</html>

CSS:

*
{
    margin: 0;
}
body
{
    background-image: url("background.jpg");
    color: white;
    font-family: Helvetica;
    padding: 0;
}
h2
{
    font-family: "Kingthings Calligraphica";
    font-size: 30pt;
    text-align: center;
    margin-top: 30%;
}
nav
{
    border: 1px solid red;
    position: fixed;
    padding: 10px 20px;
    width: 100%;
    top: 0;
}
nav div
{
    float: left;
    height: 100%;
    width: 20%;
    background-color: rgba(0,0,0,0.6);
    transition: background-color 0.5s;
}
nav div:hover
{
    background-color: rgba(0,0,0,0);
    cursor: pointer;
}
button
{
    border: 1px solid white;
    border-radius: 3px;
    background-color: rgba(0,0,0,0);
    color: white;
    padding: 10px 20px;
    width: 100%;
}

结果: screenshot

为什么导航离开屏幕但按钮没有?

1 个答案:

答案 0 :(得分:3)

这是因为你使用

width:100%;

border: 1px solid red;

等于

100% + 2px;

比你还添加padding

它只是增加了数学。

这将有效:http://jsbin.com/vubug/2/edit

nav{
    box-shadow: inset 0 0 0 1px red;
    position: fixed;
    width:100%;
    top: 0;
}

要让浏览器进行数学计算,您还可以使用calc CSS属性。 (* 2014仍为实验性)

另外值得注意的是:操作元素(inputbutton等)在浏览器甚至操作系统中的行为都不同。应用于100%宽度button的填充向内应用,同时应用于100%宽度的块级DIV元素,它向外作用增加设置宽度。

其中一个逻辑原因是你不能在block-level内有<button></button>元素(并且有一个有效的标记),这样你就可以使用该元素的padding,所以浏览器尝试弥补在内部padding空间中应用button的情况。 TEST CASE

使用CSS3 box-sizing: border-box ;

DEMO

  <div id="widthAuto">DIV {width: auto;}</div> <!-- DESIRED -->
  <div id="width100">DIV {width: 100%;}</div> <!-- OVERFLOWS -->

  <div id="fixed">DIV {position:fixed;}</div> <!-- LOOSES WIDTH -->
  <div id="fixed_width100">DIV {position:fixed; width:100%;}</div> <!-- OVERFLOWS --> 
  <div id="fixed_width100_boxSizing">DIV {position:fixed; width:100%; box-sizing: border-box;}</div>

CSS:

div{
  background:#ddd;
  border:10px solid red;
  padding:10px;
  margin-bottom:5px;
  font-family:monospace;
}
div[id^=fi]{border-color:blue}


#widthAuto{
  width:auto;
}
#width100{
  width:100%; 
}

#fixed{
  position:fixed; /* Not in flow and looses the "auto" width :( */ 
  /*just for preview*/ top:200px;  
}
#fixed_width100{
  position:fixed;
  width: 100%;    /* same issue as #width100 */
  /*just for preview*/ top:300px;  
}
#fixed_width100_boxSizing{
  position:fixed;
  width:100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  /*just for preview*/ top:400px;  
}

最简单的解决方案

或者简单地使用fixed元素作为100%宽度的虚拟包装,并将填充,边框应用于内部元素。这就是我的方式。

相关问题