CSS布局
2019-02-11 本文已影响0人
stephenoo
1.左右布局
2.左中右布局
3.水平居中
4.垂直居中
5.等其他小技巧
1.左右布局
实现方法一:直接用float
直接使用float会导致,当页面变窄,不够放右边的部分的时候,会流下去。
<div class="left"></div>
<div class="right"></div>
.left{
width: 100px;
height: 100px;
background: #000;
float: left;
}
.right{
width: 100px;
height: 100px;
background: green;
float: left; //或者右浮动
}
记得给父元素清除浮动
如果给定父元素的宽度,可以灵活运用width: num%
,来实现布局
实现方式二:margin+float
<div class="left">定宽</div>
<div class="right">自适应</div>
.left{
width: 100px;
height: 100px;
background: red;
float: left;
}
.right{
margin-left: -100px;
height: 100px;
background: yellow;
}

会发现,两个并不齐,还得调整。
实现方式三:绝对定位
<div class="left"></div>
<div class="right"></div>
.left{
width: 100px;
height: 100px;
background: #000;
position: absolute;
}
.right{
width: 100px;
height: 100px;
background: green;
position: absolute;
left:100px
}

实现方式四:inline-block
<div class="left">..</div>
<div class="right">..</div>
/*实际测试,发现50%没法用,会挤下去,不知道为啥*/
.left {
display: inline-block;
vertical-align: top;
width: 50%;
background-color: grey;
}
.right {
display: inline-block;
vertical-align: top;
width: 50%;
background-color: pink;
}
修改为48%的效果图:

2.左中右布局
实现方式一:float
<div class="left">..</div>
<div class="middle">...</div>
<div class="right">..</div>
div{
float: left;
}
.left{
width:30%;
background: #000;
}
.middle{
width:40%;
background: grey;
}
.right{
width: 30%;
background: red;
}

实现方式二:float + margin + calc(两侧定宽)
<div class="wrap clearfix">
<div class="left">..</div>
<div class="middle">...</div>
<div class="right">..</div>
</div>
.left{
width:100px;
background: #000;
float: left;
}
.middle{
width: calc(100% - 200px);
background: grey;
float:left;
}
.right{
width: 100px;
background: red;
float: right;
}

3.水平居中
行内元素:
行内元素(主要是表现为文字,图片等行内元素),通过在父级元素设置 text-align:center
使子级行内元素居中。
定宽块级元素:
为定宽块级元素设置:
margin-left: auto;
margin-right: auto;
不定宽块级元素:
方法一:设置 position:relative 和 left:50%
<div>
<ul>
<li><a href="#">我是要</a></li>
<li><a href="#">居中的</a></li>
<li><a href="#">ul标签</a></li>
</ul>
</div>
div{
display: inline-block;
position:relative;
left:50%
}
ul{
list-style:none;
margin:0;
padding:0;
position:relative;
left:-50%;
}
li{
float:left;
margin-right:8px;
}
通过给父元素设置 display:inline-block
,然后给父元素设置 position:relative
和 left:50%
,子元素设置 position:relative
和 left:-50%
来实现水平居中。
方法二:设置 display:inline 方法:
通过给父元素设置display: inline
的方法,然后用行内元素居中的方式
4.垂直居中
方式一,行内元素可以使用line-height;
方式二,定高的块级元素可以使用display:inline-block
然后同上,或者用padding来实现;
方式三:使用 position 和 transform
<div class="center">
<p>我是水平和垂直居中的。</p>
</div>
.center {
height: 200px;
position: relative;
border: 3px solid green;
}
.center p {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

5.等其他小技巧
浮动:
浮动会造成父元素塌陷



解决方法:给浮动元素的父元素,清除浮动;

宽度:
使用 max-width 替代 width 可以使浏览器更好地处理小窗口的情况
其他:
box-shadow神器
作者:索伯列夫
链接:https://www.jianshu.com/p/d04d82d70673
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。