Mitali Mitali - 2 months ago 5
CSS Question

Make fixed header's width the same size as container div

The

header
element is inside a
div
container. I set
header
as
fixed
. It causes 2 problems:


  1. The width of
    header
    overflows the width of the
    div
    element. It should match the
    div
    .

  2. The other elements
    nav
    and
    article
    are not visible when I make
    header
    as fixed.



This is how it appears now:
output

This is how I want it to appear:
Image2

here's my code snippet:



<!DOCTYPE html>
<html>
<head>
<style>
div.container {
width: 100%;
border: 1px solid gray;
}
header{
position:fixed;
width:100%;
right:0px;
}
header, footer {
padding: 1em;
color: white;
background-color: black;
clear: left;
text-align: center;
}

nav {
float: left;
max-width: 160px;
margin: 0;
padding: 1em;
}

nav ul {
list-style-type: none;
padding: 0;
}

nav ul a {
text-decoration: none;
}

article {
margin-left: 170px;
border-left: 1px solid gray;
padding: 1em;
overflow: hidden;
}
</style>
</head>
<body>

<div class="container">

<header>
<h1>City Gallery</h1>
</header>

<nav>
<ul>
<li><a href="#">London</a></li>
<li><a href="#">Paris</a></li>
<li><a href="#">Tokyo</a></li>
</ul>
</nav>

<article>
<h1>London</h1>
<p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p>
<p>Standing on the River Thames, London has been a major settlement for two millennia, its history going back to its founding by the Romans, who named it Londinium.</p>
</article>

<footer>Copyright © W3Schools.com</footer>

</div>

</body>
</html>




Answer

This gives me result you wanted:

header {
/* Everything else is same as your code*/
position: relative;
}
header,footer {
/* Everything else is same as your code*/
padding: 1em 0;
}
  1. You set div width 100%, and header width 100% of its parent, and then set padding left and right of 1em (padding: 1em -> its padding from all 4 sides, padding:1em 0 -> top&bottom 1em, left&right 0).
  2. why did you set fixed? Do you need header to be sticky to top?
div.container {
  width: 100%;
  border: 1px solid gray;
}
header{
  position:fixed;
  width:100%;
}
header, footer {
  /*padding: 1em 0;*/
  color: white;
  background-color: black;
  clear: left;
  text-align: center;
}
header h1 {
  line-height: 2em;
  font-size: 2em;
}
nav {
  float: left;
  max-width: 160px;
  margin: 0;
  padding: 1em;
  margin-top: 6em;
}
nav ul {
  list-style-type: none;
  padding: 0;
}
nav ul a {
  text-decoration: none;
}
article {
  margin-left: 170px;
  border-left: 1px solid gray;
  padding: 1em;
  overflow: hidden;
  margin-top: 6em;
}