css style common horizontal / vertical center

Centered style, are more commonly used method, it does not have the conventional example is not enough to use these types of

1/2 of the width and height are fixed
3 people think it is best to use, you can not consider the width and height issue
  1. text-align:center;

    <div class="box">
    	<span>测试文字</span>
    </div>
    
    .box{
    	width:120px;
    	height:100px;
    	background:#000;
    	text-align: center;
    	line-height:100px;
    }
    

    Here Insert Picture Description

  2. margin:auto;

    1. Element is a block element must be centered
      <div class="box">
      	<span>测试文字</span>
      </div>
      
      .box{
      	background: #000;
      	color: #FFF;
      	width: 120px;
      	height: 70px;
      	padding-top: 30px;
      }
      .box span{
      	display: block;
      	width: 64px;
      	border: 1px solid #fff;
      	margin: auto;
      }
      
      Here Insert Picture Description
    2. Positioned elements
      <div class="box">
      	<span>测试文字</span>
      </div>
      
      .box{
      	background: #000;
      	color: #FFF;
      	width: 120px;
      	height: 100px;
      	position: relative;
      }
      .box span{
      	width: 64px;
      	height: 24px;
      	position: absolute;
      	border: 1px solid #fff;
      	left: 0;
      	right: 0;
      	top: 0;
      	bottom:0;
      	margin: auto;
      }	
      
      Here Insert Picture Description
  3. transform: translate(-50%,-50%);

    <div class="box">
    	<span>测试文字</span>
    </div>
    

    There are two methods css (margin / position)

    1. We need to be clear box width and height
      .box{
      	background: #000;
      	color: #FFF;
      	width: 140px;
      	height: 100px;
      }
      .box span{
      	border: 1px solid #fff;
      	float: left;
      	margin: 50px 0 0 70px;
      	transform: translate(-50%,-50%);
      }
      
      Here Insert Picture Description
    1. Without calculation outer width and height, the positioning need to use
      .box{
      	background: #000;
      	color: #FFF;
      	width: 140px;
      	height: 100px;
      	position: relative;
      }
      .box span{
      	border: 1px solid #fff;
      	position: absolute;
      	left: 50%;
      	top: 50%;
      	transform: translate(-50%,-50%);
      }
      
      Here Insert Picture Description
Released seven original articles · won praise 3 · Views 5021

Guess you like

Origin blog.csdn.net/qq_39882537/article/details/104968202