上中下三栏布局:http://www.javashuo.com/article/p-ceyncsea-v.htmljavascript
注:这里说的元素都是子元素,居中也是子元素。css
#father {
// display:block; 若是父级不是块 得先转块 width: 500px; height: 300px; background-color: skyblue; text-align: center; }
定宽:只需给定宽的子元素设置 margin:0 auto;便可html
#father { width: 500px; height: 300px; background-color: skyblue; } #son { width: 100px; height: 100px; background-color: green; margin: 0 auto; // 加这个 }
不定宽:一、设置为行内 二、定位 三、css3得 transform 四、flexbox布局java
#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%) }
四、flexbox ( 宽度定不定 均可以)css3
#father { width: 500px; height: 300px; background-color: skyblue; display: flex; justify-content: center; // 水平居中 } #son { width: 100px; height: 100px; background-color: green; }
单行行内:子元素与父盒子等高;app
多行行内:父元素table布局布局
#father { width: 500px; height: 300px; background-color: skyblue; display: table-cell; vertical-align:middle; // 垂直居中 } #son { background-color: green; }
一、定高定位flex
#father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { height: 100px; background-color: green; position: absolute; top: 50%; margin-top: -50px; }
二、不定高 css3 transformflexbox
#father { width: 500px; height: 300px; background-color: skyblue; position: relative; } #son { background-color: green; position: absolute; top: 50%; transform:tanslateY(-50%); }
三、flex box ( 高度定不定 均可以).net
#father { width: 500px; height: 300px; background-color: skyblue; display: flex; align-items: center; // 垂直居中 } #son { width: 100px; height: 100px; background-color: green; }
3、水平垂直居中
知宽高:定位
一、设置父元素为相对定位,给子元素设置绝对定位,top: 0; right: 0; bottom: 0; left: 0; margin: auto;
二、设置父元素为相对定位,给子元素设置绝对定位,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; }
不知宽高:
一、定位
#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%); }
二、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