简体   繁体   English

jQuery CSS如何使用保证金:0自动

[英]Jquery CSS How To Use Margin: 0 auto

I'm new to Jquery. 我是Jquery新手。 I want to know how can we use margin: 0 auto; 我想知道如何使用margin:0 auto; CSS code in jquery scripting. jQuery脚本中的CSS代码。 Could anyone please help me out? 有人可以帮我吗? Here's the code: 这是代码:

<style>
#fixed-bar {
    padding: 0;
    background-color: black;
    z-index: 100;
}
</style>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>

<script>
$(function () {
  $("#fixed-bar")
    .css({
        "position": "fixed",
        "width": "960px",
        "margin": "0 auto",
        "top": "0px",

})
    .hide();
  $(window).scroll(function () {
    if ($(this).scrollTop() > 400) {
      $('#fixed-bar').fadeIn(200);
    } else {
      $('#fixed-bar').fadeOut(200);
    }
  });
});
</script>
<div id='fixed-bar'>
  Hello
</div>

Actually I want to center the bar. 其实我想居中。 How can I do this? 我怎样才能做到这一点?

You are setting everything correct. 您设置的一切正确。 But you cannot center an element with margin: auto that has position: fixed : 但是您不能将元素的margin: auto具有position: fixed margin: auto

Center a position:fixed element 居中位置:固定元素

You could also do this with jQuery: 您也可以使用jQuery:

Using jQuery to center a DIV on the screen 使用jQuery在屏幕上居中放置DIV

You can't use shorthand CSS with jQuery, you would have to set each margin separately. 您不能将简写CSS与jQuery一起使用,而必须分别设置每个边距。

css({
    "marginTop": "0",
    "marginRight": "auto",
    "marginBottom": "0",
    "marginLeft": "auto"
})

You can try this : 您可以尝试以下方法:

HTML: HTML:

<div id="fixed-bar">
    <p>Test</p>
</div>

CSS: CSS:

body {
    position : relative;
}

#fixed-bar {
    padding: 0;
    background-color: black;
    z-index: 100;
    width: 960px;
}

JavaScript: JavaScript:

$("#fixed-bar").css({
                "position" : "absolute",
                "left" : (($(window).width() - $("#fixed-bar").outerWidth()) / 2) + $(window).scrollLeft() + "px" })
               .hide();

$(window).scroll(function () {
    if ($(this).scrollTop() > 400) {
        $('#fixed-bar').fadeIn(200);
    } else {
        $('#fixed-bar').fadeOut(200);
    }
});

This way your element will be horizontally centered regardless of screen size. 这样,无论屏幕大小如何,元素都将水平居中。 Don't forget to include jQuery in your HTML. 不要忘记在HTML中包含jQuery。

有更好的方法使用jQuery将div居中,例如将其设置为绝对位置并查找其宽度,视口宽度,并根据这些数字设置偏移量:

$('.mydiv').css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM