[英]how to fix position vertically and absolute horizontally for a division
I'm trying to fix header vertically and absolute horizontally. 我正在尝试垂直和绝对水平固定标题。 I am using the following codes.
我正在使用以下代码。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="header_position.js" type="text/javascript"></script>
</head>
body tag 身体标签
$(window).scroll(function(event) {
$("#headerpos").css("margin-left", 0-$(document).scrollLeft());
});
#headerpos{
position:fixed;
border-top:8px solid #8DC540;
background:#1E415B;
width:956px;
padding-bottom:7px;
margin:auto;
z-index:100;
}
I tried using class attrb in div
as well as id attrb 我尝试在
div
和id attrb中使用class attrb
.header{
position:fixed;
border-top:8px solid #8DC540;
background:#1E415B;
width:956px;
padding-bottom:7px;
margin:auto;
z-index:100;
}
Also tried by removing margin:auto
; 也尝试通过删除
margin:auto
;
I saw this all from the link Position a Div "Fixed" Vertically and "Absolute" Horizontally within a "Position:Relative" Container Div 我从链接在“ Position:Relative”容器Div中将“垂直固定” Div和“绝对”水平“ Div”链接中看到了所有这些
But it is not working and in Chrome if I go to inspect element I see an error: 但是它不起作用,在Chrome中,如果我要检查元素,则会看到错误:
Uncaught Reference error: $ is not defined (at line 1)
未捕获的参考错误:未定义$(在第1行)
Please help. 请帮忙。 It's very important.
这很重要。
You need to include jQuery in the head of your page like this: 您需要像这样在页面的顶部包含jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="header_position.js" type="text/javascript"></script>
Also, be sure to wrap your jQuery in a document ready call: 另外,请确保将jQuery包装在文档就绪调用中:
$(document).ready(function () {
$(window).scroll(function (event) {
$("#headerpos").css("margin-left", 0 - $(document).scrollLeft());
});
});
If $
is not defined, you'll need jQuery. 如果未定义
$
则需要jQuery。 Just include 只包括
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
before the other script. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
之前的其他脚本。
I also recommend putting both script
tags at the bottom of the page to make it load faster. 我还建议将两个
script
标签都放在页面底部,以加快加载速度。
if you are using fixed positioning in css, you don't need js to centeralign a div horizontally. 如果您在CSS中使用固定位置,则不需要js将div水平居中对齐。 try this.
尝试这个。
.header{
position:fixed;
border-top:8px solid #8DC540;
background:#1E415B;
width:956px;
padding-bottom:7px;
margin-left:-478px;
left:50%;
z-index:100;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.