Search code examples
htmlcsspositionfixed

Position: Fixed; Not working properly


I'm just getting started coding and have run into some problems while trying to use position: fixed; in CSS during one of my practice sessions.

This is what I want things to look like (affected area highlighted red): WHAT I WANT WHAT I WANT

I want the red header to be in a fixed position as the user scrolls down the page like on facebook or youtube. I have applied a z-index: 1; (as currently it is the only indexed item on the page) and a position: fixed;. This results in the header being fixed and scrolling as I want but it fixes it 40-50px down from the top of the page which is not what i want! See image here:

WHAT I GET WHAT I GET

Obviously I'm missing something obvious but I'm tearing my hair out trying to find it!

Can anyone help?

See my HTML and CSS code below.

body{
	margin: 0px;
	background-color: #dddddd;
}

#container {
}

#header {
	background-color: red;
	width: 100%;
	height: 50px;
	position: fixed;
	z-index: 10;
}

#video {
	background-color: #ffffff;
	width: 650px;
	height: 400px;
	float: left;
	margin: 5px;
	margin-left: 120px;
	margin-top: 50px;
	margin-bottom: 35px;
}

#description {
	background-color: #ffffff;
	width: 650px;
	height: 200px;
	float: left;
	margin: 5px;
	margin-left: 120px;
	margin-bottom: 35px;
}

#comments {
	background-color: #ffffff;
	width: 650px;
	height: 400px;
	float: left;
	margin: 5px;
	margin-left: 120px;
	margin-bottom: 35px;
}

#rightadbox {
	background-color: #ffffff;
	width: 350px;
	height: 100px;
	margin: 5px;
	margin-top: 50px;
	margin-left: 800px;
	margin-bottom: 35px;
}

#right {
	background-color: #ffffff;
	width: 350px;
	height: 1000px;
	margin: 5px;
	margin-left: 800px;
	margin-bottom: 35px;
}
#footer {
	background-color: blue;
	width: 100%;
	height: 100px;
	clear: both;
}
<!DOCTYPE HTML>
<html>
	<head>
		<!--PUT CSS LINK HERE-->
		<link rel="stylesheet" type="text/css" href="PracticeHTMLCSS.css"/>
		<title>Practice HTML</title>
	</head>
	<body>
		<div id="container">
			<div id="header">
			</div>
			<div id="video">
			</div>
			<div id="description">
			</div>
			<div id="comments">
			</div>
			<div id="rightadbox">
			</div>
			<div id="right">
			</div>
			<div id="footer">
			</div>
		</div>
	</body>
</html>


Solution

  • Try adding top: 0; To your header id in the css file. As your header does not know where to be placed. This will make the distance from the header to the top of your page zero, hence solving your issue

    #header {
        background-color: red;
        width: 100%;
        height: 50px;
        position: fixed;
        z-index: 10;
        top: 0; <-- 
    }