1. 程式人生 > >css已知寬度,高度/不知道寬度,高度 盒子垂直居中

css已知寬度,高度/不知道寬度,高度 盒子垂直居中

1.已知寬度,高度,水平居中

<style>
			.content{
				width: 300px;
				height: 150px;
				background: red;
			}
			.content>input{
				width: 30px;
				height: 30px;
			display: block;
			margin:0 auto;
			}
			
		</style>
<div class="content">
  	<input type="button" value="123" />
  </div>

水平居中,需要最外層盒子固定寬度,裡面input轉化為block,在給一個margin:0 auto 就可以水平居中了

2.已知寬度,高度,垂直居中

	.content{
				width: 300px;
				height: 150px;
				background: red;
				position: relative;
			}
			.content>input{
				width: 30px;
				height: 30px;
			display: block;
		position: absolute;
		top: 50%;
		margin: -15px;
		left: 50%;
		
	
			}
 <div class="content">
  	<input type="button" value="123" />
  </div>

垂直居中,需要外面盒子給個position:relative 裡面的input 需要絕對定位,其中top,left分別設定為50%,margin-let,margin-top設定為寬度和高度的負一半

3 不知道盒子寬度高度

(1) 設定 父元素的display:table 設定子元素的display:table-cell 即可

<style>
			
			.body1{
				width: 100%;
				height: 100%;
				background: indianred;
				display: table;
			}
			.div1{
			
				 display: table-cell;
    text-align: center;
vertical-align:middle
    color: #fff;
    font-size: 16px;
			}
			
			
		</style>


<div class="body1">
			
			<div   class="div1">
			
			<p>你好你好</p>
			<p>你好你好</p>
			<p>你好你好</p>
			
			<p>你好你好</p>
			<p>你好你好</p>
			<p>你好你好</p>
			
			<p>你好你好</p>
			<p>你好你好</p>
			
		</div>
		</div>

(2) 使用display:flex佈局 設定justify-content: center;

<style>
			
			.body1{
				width: 100%;
				height: 100%;
				background: indianred;
                display: flex;
	            justify-content: center;
                 align-items: center;
			
			}
			.div1{
			
	
    color: #fff;
    font-size: 16px;
			}
			
			
		</style>


<div class="body1">
			
			<div   class="div1">
			
			<p>你好你好</p>
			
			
		</div>
		</div>

(3) 使用position:absolute ,transform

<style>
			*{
				margin: 0;
				padding: 0;
			}
			
			.div1{
			
	position: absolute;
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
  background: red;
    font-size: 16px;
			}
			
			
		</style>	


<div   class="div1">
			
			<p>你好你好</p>
				<p>你好你好</p>
					<p>你好你好</p>
					
						
			
		</div>