html+css布局技巧

(一)、父元素的宽高的变化子元始终素铺满父元素

<body>
	<div class="parent">
		<div class="child"></div>
	</div>
</body>



<style type="text/css">
	.parent{
		position: relative;
		background: blue;
		width: 800px;
		height: 800px;
		margin: 0 auto;
	}
	.child{
		position: absolute;
		background: red;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
	}
</style>

(二)、子元素位于父元素正中心

<div class="parent">
	<div class="child"></div>
</div>



<style type="text/css">
	.parent{
	    position: relative;
		background: blue;
		width: 50%;
		height: 500px;
		margin: 0 auto;
	}
	.child{
		position: absolute;
		background: red;
		width: 100px;
		height: 100px;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		margin: auto;
	}
</style>

(三)、子元素垂直居中

<div class="parent">
	<div class="child"></div>
</div>



<style type="text/css">
	.parent{
		position: relative;
		background: blue;
		width: 50%;
		height: 500px;
		margin: 0 auto;
	}
	.child{
		position: absolute;
		background: red;
		width: 100px;
		height: 100px;
		top: 0;
		bottom: 0;
		margin: auto;
	}
</style>

(四)子元素水平居中

<div class="parent">
	<div class="child"></div>
</div>



<style type="text/css">
	.parent{
		position: relative;
		background: blue;
		width: 50%;
		height: 500px;
		margin: 0 auto;
	}
	.child{
		position: absolute;
		background: red;
		width: 100px;
		height: 100px;
		left: 0;
		right: 0;
		margin: auto;
	}
</style>

(五)固定宽高比盒子,padding-bottom的取值是参照width,如果width的值是百分比,那么参照就是父元素的width值

<div class="parent">
	<div class="child">
		<div class="grandson"></div>
	</div>
</div>




<style type="text/css">
	body{
		height: 900px;
	}
	.parent{
		background: blue;
		overflow: hidden;
		width: 100%;
		height: 0;
		padding-bottom: 50%;
		margin: 0 auto;
	}
	.child{
		background: red;
		overflow: hidden;
		width: 50%;
		height: 0;
		padding-bottom: 50%;
		margin: auto;
	}
	.grandson{
		background: yellow;
		overflow: hidden;
		width: 50%;
		height: 0;
		padding-bottom: 50%;
		margin: auto;
	}
</style>

(六)文字多于容器宽度显示省略号

overflow: hidden 
white-space: nowrap
text-overflow: ellipsis

(七)box-sizing

属性值:content-box、border-box

content-box:盒子的真实width = width+padding +border (标准盒模型)

border-box:盒子的真实width = width  (IE盒模型)

使用场景:

1. 当需要两个宽度为50%的div确保并列时,设置box-sizing:border-box; 
此时的width:50%是content+padding+border的宽度。

2. 解决input标签在各个浏览器中的兼容性问题

<div class="top"></div>
<hr>
<div class="bottom"></div>


<style type="text/css">
	div{
		width: 500px;
		height: 200px;
		padding: 0 20px;
		margin: 0 20px;
		border: 20px solid #567;
		background: #2e4
	}
	.top{
		box-sizing: content-box;
	}
	.bottom{
		box-sizing: border-box;
	}
</style>

参考:https://blog.csdn.net/orichisonic/article/details/49123697

猜你喜欢

转载自blog.csdn.net/let4897/article/details/82935721