下面说两种在屏幕正中(水平居中+垂直居中)的方法
放上示范的html代码:
<body>
<div class="main">
<h1>MAIN</h1>
</div>
</body>
1
2
3
4
5
方法一:
div使用绝对布局,设置margin:auto;并设置top、left、right、bottom的值相等即可,不一定要都是0。
.main{
text-align: center; /让div内部文字居中/
background-color: #fff;
border-radius: 20px;
width: 300px;
height: 350px;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
方法二:
仍然是绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样,所以再用transform向左(上)平移它自己宽度(高度)的50%,也就达到居中效果了,效果图和上方相同。
.main{
text-align: center;
background-color: #fff;
border-radius: 20px;
width: 300px;
height: 350px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
1
2
3
4
5
6
7
8
9
10
11
方法三:
对于水平居中,可以使用最简单的<center>标签,不过已经过时了,用法如下:
<p><center>123</center></p>
1
这个<center>标签就是相对于<p>标签里的文字,可以使其居中。
由于center标签已经过时了,所以正规一点的话还是不建议使用的,可以使用如下的方式代替:
<p style="text-align:center;">123</p>
左右布局
左侧定宽,右侧自适应
float + margin
.left {
float: left;
width: 200px;
height: 100%;
background-color: red;
}
.right {
margin-left: 200px;
background-color: blue;
}
1
2
3
4
5
6
7
8
9
10
float + overflow:hidden
利用overflow:hidden形成BFC,因为BFC不会与float box重叠。
.left {
float: left;
width: 200px;
height: 100%;
background-color: red;
}
.right {
overflow:hidden;
background-color: blue;
}
1
2
3
4
5
6
7
8
9
10
CSS3 float + calc
.left {
float: left;
width: 200px;
height: 100%;
background-color: red;
}
.right {
float: left;
width: calc(100% - 200px);
height: 100%;
background-color: blue;
}
1
2
3
4
5
6
7
8
9
10
11
12
弹性布局
.parent {
display: flex;
}
.left {
width: 200px;
height: 100%;
background-color: red;
}
.right {
display: flex;
flex: 1;
height: 100%;
background-color: blue;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
当然,使用absolute定位也是可以的,通过left调整位置就可以了。
左中右布局
结构说明:左右两部分宽度固定,中间的部分填充剩余所有宽度。
常用场景:最左边摆放一张图片,中间摆放说明性文字,右边摆放相关操作的小图标。
之前的做法虽然有实现但是不完美。思路如下(简单描述为左中结构):
首先考虑中间的要拉伸铺满剩下的宽度,必须宽度设置成百分比100%,用box-sizing设置为border-box,然后配合padding,给左右留固定的宽度,左右的内容放到padding区域与其重叠,使用float浮动是不能重叠的,所以一定要有一个是绝对定位,全部都使用绝对定位是没有问题的,但是绝对定位有个特性,定位的元素从文档流中删除,不占用空间,导致父元素不能自动适应高度,如果全部都绝对定位,父元素不显示指定高度,那么高度会为0,导致后面的元素和要排列的左中右结构重叠了。浮动元素本来也是脱离了文档流,不占用空间,但是父元素设置成内联块之后,它能占用空间(不理解内联块的性质)。于是就用绝对定位和浮动来混合实现,多数情况下,左边的图片宽度和高度都固定,于是就把左边的内容设置成绝对定位,中间的内容设置成浮动了,父元素再设置个最小高度为左边内容的高度,规避高度适应问题。
思路如下:
全部都用浮动,关键要解决中间元素宽度为100%之后,左中右总宽度超过父元素宽度,导致换行的问题。借助外边距margin设置为负值解决了。中间内容把padding-left设置成左右部分宽度的和,把margin-left设置成padding-left对应的负数,就缩减了真实宽度了,恰好合适。
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
<div style="display:inline-block;width:100%;">
<div style="float: left; width:100px;">
左边
</div>
<div style="float: left;box-sizing:border-box;width: 100%;padding-left: 150px;margin-left: -150px;">
中间
</div>
<!- 此处float等于left只是为了让它浮动,处在第三个节点,已经是布局的右边 ->
<div style="float: left; width:50px;">
右边
</div>
</div>
网友评论