简体   繁体   中英

html and css margin auto error

I have a container div with the class banner. In my css the following rule does not centre the banner.

Why is this?

.banner {
    width:900px;
    height:300px;
    margin:0 auto;
    background:url('img/banner-bg.jpg') top left no-repeat;
    border-radius: 20px;
    -webkit-border-radius: 20px;
    -o-border-radius: 20px;
    -moz-border-radius: 20px;
}

This is the HTML code, i can't see anything wrong with it

       <!DOCTYPE html>
       <html>
      <head>
  <title>Animated Banner CSS</title>
 <link rel="stylesheet" type="text/css" href="banner.css">
     </head>
      <body>

         <div class="banner"> 

       <img class="img-snow01" src="img/snow-back.png" width="900" height="600">
       <img src="img/foreground.png" width="335" height="1000" class="img01">
       <img class="img-snow02" src="img/snow-front.png" width="900" height="600">

            <h3 class="txt-heading01">Everthing is 30% off</h3>
       <!--<h3 class="txt-heading02"> Friday and Saturday</h3>-->
        <p class="txt01">Winter</p>
       <p class="txt02">Sale</p>
      <!---<p class="txt03">Click here</p>
       <p class="txt04"> to learn more</p>
         -->

      </div> <!-- Banner-->


       </body>
      </html>

For margin: 0 auto; to trigger a 'center align', it requires the element to have a width set . because display: block elements will always be set at 100% width by default

It is also common to set text-align:center on the parent element (in the case of the child elements being of CSS display type: inline )

 /* optional if child elements are display type of inline */
body { text-align: center; } 

/* set a width */
.page {
   width: 80%; margin: 0 auto; text-align: left;
}

Demo: http://jsfiddle.net/bBsLm/1/

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