css 样式 常用水平/垂直居中

居中样式,都是比较常用的方法,不常用的就不举例了 有这几种就够用了

1/2 都是固定宽高
3 个人觉得是最好用的,可以不考虑宽高问题
  1. text-align:center;

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

    在这里插入图片描述

  2. margin:auto;

    1. 居中元素必须是块元素
      <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;
      }
      
      在这里插入图片描述
    2. 定位元素
      <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;
      }	
      
      在这里插入图片描述
  3. transform: translate(-50%,-50%);

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

    css有两种方法(margin/position)

    1. 需要明确box的宽高
      .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%);
      }
      
      在这里插入图片描述
    1. 不用计算外层宽高,需要用到定位
      .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%);
      }
      
      在这里插入图片描述
发布了7 篇原创文章 · 获赞 3 · 访问量 5021

猜你喜欢

转载自blog.csdn.net/qq_39882537/article/details/104968202
今日推荐