//子元素为块元素,那就给父元素加上
margin: a auto
//子元素为行内元素、行内块元素,那么就给父亲加上
text-align:center
//子元素为块级元素,那么给子元素加上
margin-top:值为(父元素的content - 子元素的高度) / 2
//若子元素为行内或者行内块元素
让父元素 height= line-height 每个子元素都加上vertical-align:middle
如果想要绝对垂直居中,父元素的font-size:0
行内元素、行内块元素,彼此之间的换行会被浏览器解析为一个空白字符。
解决方案:
方案一: 去掉换行和空格(不推荐)。
方案二: 给父元素设置 font-size:0 ,再给需要显示文字的元素,单独设置字体大小(推 荐)。
行内块元素与文本的基线对齐,而文本的基线与文本最底端之间是有一定距离的。
解决方案:
方案一: 给行行内块设置 vertical ,值不为 baseline 即可,设置为 middel 、 bottom 、 top 均可。
方案二: 若父元素中只有一张图片,设置图片为 display:block 。
方案三: 给父元素设置 font-size: 0 。如果该行内块内部还有文本,则需单独设置 font:size 。
块宽想与包含块一致,可以给定位元素同时设置 left 和 right 为 0 。
高度想与包含块一致, top 和 bottom 设置为 0
方案一:
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
方案二:
left: 50%;
top: 50%;
margin-left: 负的宽度一半;
margin-top: 负的高度一半;
方案三:
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
overflow:hidden//溢出不显示
white-space:nowrap//不换行
text-overflow:ellipsis//用...表示
方法一:父容器开启 flex 布局,随后使用 justify-content 和 align-items 实现水平垂直居中
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
justify-content: center;
align-items: center;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
}
方法二:父容器开启 flex 布局,随后子元素 margin: auto
.outer {
width: 400px;
height: 400px;
background-color: #888;
display: flex;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
margin: auto;
}