zoukankan      html  css  js  c++  java
  • 垂直居中方法总结

    <style>
    	#box{
    		position: absolute;
    		margin: auto;
    		top:0px;
    		right: 0px;
    		bottom: 0px;
    		left: 0px;
    		 100%;
    		height: 30%;
    		background-color: red;
    		text-align: center;
    	}
    </style>
    <body>
    	<div id="box">
    		<h1>文字居中</h1>
    	</div>
    </body>
    

      

    第一种的好处是不用知道垂直居中的元素的高宽,但是必须设置元素的宽高!然后通过margin:auto;来达到效果。

    <style>
    	#box{
    		position: absolute;
    		top:50%;
    		left:50%;
    		transform:translate3d(-50%,50%,0);
    		background-color: red;
    		text-align: center;
    	}
    </style>
    <body>
    	<div id="box">
    		<h1>文字居中</h1>
    	</div>
    </body>
    

      

    这种的好处是宽高不用定义!

    <style>
    	.box{  
    	    display: flex;  
    	    height: 400px;  
    	    align-items:center;  
    	    justify-content:center;
    	    background: #0099cc  
    	}  
    	h1{  
    		display: flex;  
    	    align-items:center;  
    	    justify-content:center;
    	}  
    </style>
    <body>
    	<div class="box">  
    	    <h1>实现元素水平居中</h1>  
    	</div> 
    </body>
    

      

    想要让那个元素居中,就在其父元素加 display:flex;justify-content:center;align-items:center;

    按照原理,往body里设置这3个样式,就能按body垂直居中,但是没有,是因为body的默认高度为0px;在给个height:600px;就会有效果的!

    <style>
    	#container{
    		position: absolute;
    		top:0px;
    		right: 0px;
    		bottom: 0px;
    		left: 0px;
    		display: flex;
    		justify-content:center;
    		align-items:center;
    	}
    	.box{  
    	    display: flex;  
    	    height: 400px;  
    	    align-items:center;  
    	    justify-content:center;
    	    background: #0099cc  
    	}  
    	h1{  
    		display: flex;  
    	    align-items:center;  
    	    justify-content:center;
    	}  
    </style>
    <body>
    	<div id="container">
    		<div class="box">  
    		    <h1>实现元素水平居中</h1>  
    		</div>
    	</div> 
    </body>
    

      

    对于移动端,这是我常用的一种方法,这样屏幕的宽高就都有了!

  • 相关阅读:
    java中的多线程
    PSCollectionView瀑布流实现
    直接拿来用!最火的iOS开源项目(一~三)
    iOS6新特征:UICollectionView介绍
    mac os颜色拾取工具/软件/器推荐
    ios/object-c中的UIColor一些比较偏的颜色展示/示例
    UIColor和 同 CIColor 与 CGColor 之间的联系、转换
    IOS开发自定义CheckBox控件
    IOS常用的第三方开发库
    JVM -XX: 参数介绍
  • 原文地址:https://www.cnblogs.com/luguiqing/p/6506004.html
Copyright © 2011-2022 走看看