Day4 打卡 居中
每日一句
Your faith is all that keeps me going.
你的信任是我前进的动力。
Tips:
- 父级元素必需是块级盒子容器
- 不可自由嵌套的元素 子元素必需是内联元素如:
h1 ~ h6
caption
p
hr
特殊的元素dt只存在dl下的第一个子元素
如果p标签是h1就会出现<p><h1></h1></p> => <p></p><h1></h1><p></p>
实现子元素水平居中
- 如果子元素是行内元素,父级元素设置
text-align:center - 如果子元素是块级元素,子元素有定宽和不定宽两种情况
定宽不定位:
width: 200px;margin:0 auto;
定宽不定位:给父,子元素设定box-sizing:border-box,然后给父级设置padding-left / padding-right / margin-left / margin-right; [公式:(父宽-子宽)/2]
定宽定位:父相子绝position:absolute;left:50%;margi-left: -子宽一半;或position:absolute;left:50%;transform:translateX(-50);\
- 弹性布局:
display:flex; flex-direction:row; justify-content: center;
实现子元素垂直居中
- 如果子元素是行内元素且只有一行,父级设置
line-height:30px; - 如果子元素是行内元素且是多行,父级设置
display: inline\inline-block;\table-cell; vertical-align: middle - 如果子元素是块级元素,子元素有定高和不定高两种情况
定高不定位:给父,子元素设定
box-sizing:border- box,然后给父级设置padding-top / padding-bottom / margin-top / margin-bottom; [公式:(父高-子高)/2];
定高定位:父相子绝position:absolute;top:50%;margin-top: -子高一半;或position:absolute;top:50%;transform:translateY(-50);
- 弹性布局:
display:flex; flex-direction:column; justify-content: center;
实现子元素水平垂直居中
- 父相子绝
子元素定宽高
top:50%;left:50%;margin-left: -子宽一半;margin-top:-子高一半
子元素不定宽高top:50%;left:50%;transform:translate(-50%, -50%)
- 弹性布局
display: flex; align-items: center; justify-content: center;