Jquery CSS How To Use Margin: 0 auto

I'm new to Jquery. I want to know how can we use margin: 0 auto; CSS code in jquery scripting. 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 :

Center a position:fixed element

You could also do this with jQuery:

Using jQuery to center a DIV on the screen


你不能在jQuery中使用简写CSS,你将不得不单独设置每个页边距。

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

You can try this :

HTML:

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

CSS:

body {
    position : relative;
}

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

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.

链接地址: http://www.djcxy.com/p/75804.html

上一篇: CSS,修正了jquery水平对齐的标题

下一篇: jQuery的CSS如何使用保证金:0自动