# Css 面试
# 1.如何居中 div?
已知宽度, block 元素:
添加 margin:0 auto 属性。
div {
width: 200px;
margin: 0 auto;
}
已知宽度, 绝对定位的 div 居中:
div {
position: absolute;
width: 300px;
height: 300px;
margin: auto; /* 这一步很关键 */
top: 0;
left: 0;
bottom: 0;
right: 0;
background-color: pink; /* 方便看效果 */
}
未知宽度,fit-content:(兼容性很差)
div {
width: fit-content;
margin: auto;
background-color: pink; /* 方便看效果 */
}
未知宽度,inline-block:
.parent {
text-align: center;
}
div {
display: inline-block;
background-color: pink; /* 方便看效果 */
}
未知宽度/已知宽度,relative: 需要两个 div,外层 left 50%,内层 left -50%。
用 float 或 inline-block,使容器大小为内容大小,而非默认的 100%。
.outter {
display: inline-block; /* or float: left; */
position: relative;
left: 50%;
}
.inner {
position: relative;
left: -50%;
}
left 的值为百分比时,为父容器的宽度的百分比(MDN)。