简体   繁体   中英

css: margin 0 auto working in IE8 but not in chrome

My css is here (Fiddle Link) .

<div id="yearDiv">
        <ul>
            <li><a href="#">2014</a></li>
            <li><a href="#">2012</a></li>
            <li><a href="#">2011</a></li>
            <li><a href="#">2010</a></li>
        </ul>
    </div>


#yearDiv{

    background-color: #eee;
    height: 100%;
    width: 30%;
    margin-left: 3%;
    float: left;
}

#yearDiv ul{

    margin: 0 auto;

}

#yearDiv li{

    list-style: none;
    margin: 15px auto;
    display: block;

}

#yearDiv li a{

    text-decoration: none;
    text-align: center;
    display: block;
    color:#a30f0f;
    font-family:Arial;
    font-size:35px;
    font-weight:bold;
    font-style:normal;
    background: #eee;
    border-color: #7C1D1B #711C17 #6A1F1C #7C1D1B;
    border: 2px solid;
    font-family: Courier New;
    width: 150px;
    height: 50px;

}

#yearDiv li a:LINK, #yearDiv li a:VISITED {



}

#yearDiv li a:HOVER, #yearDiv li a:ACTIVE {



}

On IE 8 it is rendered as this

在此处输入图片说明

whereas on chrome it is rendered as

在此处输入图片说明

It seems to me that margin left is not working. I want to know how to get the links inside the div without leaving that much margin.

You should try this-

#yearDiv ul{

    margin: 0 auto;
    padding: 10px;

}

DEMO

The reason the margin is not working, is because the ul and li elements don't have a specified width.

The easiest (and I think best) solution, is to move the width property from the a element to the ul element.

Also, you should remove the padding from the ul . So the css for the ul becomes:

#yearDiv ul{
    margin: 0 auto;
    padding: 0;
    width: 150px;
}

The width is removed from the a elements. Result is: FIDDLE

NB: I though you wanted the 'buttons' to be fixed width, centered in the variable width div . Seeing Maddy's answer, I think I might be wrong in this assumption. Anyway, I hope this answer still helps you understand what the issue was, regardless of the solution you will use in the end.

My solution: give the ul a fixed width so margin: 0 auto will work for centering it. Maddy's solution: Don't specify a width for ul , li and a at all; give the div a padding and let the (block styled) elements just fill the available space. In either case, you shouldn't specify a width for the li and a elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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