【CSS】margin:0 auto;——使用条件/应用场景/不生效无效果的原因

margin:0 auto;在不同场景下生效条件如下:

        块级元素:给定要居中的块级元素的宽度。

        行内元素:①设置display:block;②给定要居中的行内元素的宽度。(行内元素设置成块级元素后可以对其宽高进行设置)

        行内块元素:设置display:block。(如input、button、img等元素,自带宽度可以不用设置其宽度)


        ①所有元素也可以通过对父元素设置 text-align:center;的方式来实现居中。(而对于块元素来说,对要居中的元素自身进行设置text-align:center也能实现居中——而无需对其父元素进行设置)

        ②margin:0 auto;可以使盒子居中,text-align:center;可以使文本居中,故有时需要两者结合使用才能使得盒子及其中文本一起居中。例如:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">

        <style>
			
			  *{
			  	 margin:0;
			  	 padding:0;
			  }
			 .box{
			 	  width:640px;
			 	  height:585px;
			 	  border:1px solid #BBBBBB;
			 	  border-top:3px solid #094683;
			 	  margin:10px auto;

			 }

			 .title{

			 	 width:600px;
                                 margin: 0 auto;         /*使盒子居中*/
                                 text-align: center;     /*使文本居中*/
			 	 margin-top:26px;
			 	 border-bottom:1px solid #CCCCCC;
				 padding-bottom:10px;

			 }

			 .title h2{
			 	 font-weight:normal;
			 	 margin-bottom:10px;
			 }
			 .title h6{
			 	 font-size:12px;
			 	 font-weight:normal;
			 	 color:#999999;
			 }

			 .title span{
			 	 color:#990000;
			 }

			 .photo{
			 	 margin:0 auto;
			 	 width:567px;
			 	 height:427px;

			 	 margin-top: 10px;
			 }
        </style>
    </head>
    <body>

          <div class="box">
          	
          	   <div class="title">
          	   	   <h2>鲁能热身赛大胜</h2>
          	   	   <h6>
          	   	   	2015年08月08日 18:19  <span>新浪体育</span> 微博 我有话说(<span>106712</span>人参与) 收藏本文
          	   	   </h6>
          	   </div>
          	   <div class="photo">
          	   	  <img src="tiyu.png">
          	   </div>
          </div>
    </body>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_39068791/article/details/80635316