居中
上中下三栏布局:https://www.cnblogs.com/menggirl23/p/10057570.html
一、水平居中
注:这里说的元素都是子元素,居中也是子元素。
行内元素:父级必须为块,子元素为行内
#father {
// display:block; 如果父级不是块 得先转块
width: 500px;
height: 300px;
background-color: skyblue;
text-align: center;
}
块级元素:宽度定不定两种
定宽:只需给定宽的子元素设置 margin:0 auto;即可
#father {
width: 500px;
height: 300px;
background-color: skyblue;
}
#son {
width: 100px;
height: 100px;
background-color: green;
margin: 0 auto; // 加这个
}
不定宽:1、设置为行内 2、定位 3、css3得 transform 4、flexbox布局
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 50%;
margin-left: -50px; // 或者 transform:translateX(-50%)
}
4、flexbox ( 宽度定不定 都可以)
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
justify-content: center; // 水平居中
}
#son {
width: 100px;
height: 100px;
background-color: green;
}
二、垂直居中
行内
单行行内:子元素与父盒子等高;
多行行内:父元素table布局
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: table-cell;
vertical-align:middle; // 垂直居中
}
#son {
background-color: green;
}
块级元素
1、定高定位
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
height: 100px;
background-color: green;
position: absolute;
top: 50%;
margin-top: -50px;
}
2、不定高 css3 transform
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
background-color: green;
position: absolute;
top: 50%;
transform:tanslateY(-50%);
}
3、flex box ( 高度定不定 都可以)
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
align-items: center; // 垂直居中
}
#son {
width: 100px;
height: 100px;
background-color: green;
}
三、水平垂直居中
知宽高:定位
1、设置父元素为相对定位,给子元素设置绝对定位,top: 0; right: 0; bottom: 0; left: 0; margin: auto;
2、设置父元素为相对定位,给子元素设置绝对定位,left: 50%; top: 50%; margin-left: --元素宽度的一半px; margin-top: --元素高度的一半px;
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
width: 100px;
height: 100px;
background-color: green;
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
不知宽高:
1、定位
#father {
width: 500px;
height: 300px;
background-color: skyblue;
position: relative;
}
#son {
background-color: green;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
2、flex
#father {
width: 500px;
height: 300px;
background-color: skyblue;
display: flex;
justify-content: center;
align-items: center;
}
#son {
background-color: green;
}
原文链接:https://blog.csdn.net/weixin_37580235/article/details/82317240

浙公网安备 33010602011771号