LearningRecord
LearningRecord copied to clipboard
常见的几种布局?垂直水平居中的多种实现方法?等高栏的几种实现方法?
常见的几种布局: 文档流布局,浮动布局,定位布局,flex布局
html:
<div class="parent">
<div class="child">
<div class="box">box</div>
</div>
</div>
水平居中:
.child{
width:200px;
margin:0 auto;
}
垂直水平居中: 一:绝对定位 1.
.parent {
position: relative;
}
.child {
width: 200px;
height: 200px;
position: absolute;
left: 0;
top: 0;
bottom: 0;
right: 0;
margin: auto;
}
2.margin 负间距
.child{
width:200px;
height: 200px;
position: absolute;
left:50%;
top:50%;
margin-left:-100px;
margin-top:-100px;
}
- Transforms 变形
.child {
width: 200px;
height: 200px;
position:absolute;
left:50%; /* 定位父级的50% */
top:50%;
transform: translate(-50%,-50%); /*自己的50% */
}
二.flex布局,使用于不定宽高布局 1.
.parent {
display: flex;
justify-content:center;
align-items:center;
}
.parent {
display: flex;
}
.child {
margin: auto
}
三:父元素设置teable-cell元素,利用三层结构模拟父子结构
.parent {
display: table;
width: 200px;
height: 200px;
}
.child {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.box {
display: inline-block;
}
四:grid布局 1.
.parent {
display: grid;
}
.child {
justify-self: center;
align-self: center;
}
.parent {
display: grid;
}
.child {
margin: auto;
}
等高栏的几种实现方法? 1.
.parent {
position: reletive
}
.child {
position: absolute;
top:0;
bottom: 0;
overflow:auto
}
.parent {
display: flex;
}
.child {
flex: 1
}
自适应高度 1.
<div class="outer">
<div class="A"> 头部DIV </div>
<div class="B">下部DIV </div>
</div>
body { height: 100%; padding: 0; margin: 0; }
.outer { height: 100%; padding: 100px 0 0; box-sizing: border-box ; position: relative; }
.A { height: 100px; background: #BBE8F2; position: absolute; top: 0 ; left: 0 ; width: 100%; }
.B { height: 100%; background: #D9C666; }
<div class="outer">
<div class="A">头部DIV</div>
<div class="B">下部DIV</div>
</div>
body { height: 100%; padding: 0; margin: 0; }
.outer { height: 100%; padding: 100px 0 0; box-sizing: border-box ; }
.A { height: 100px; margin: -100px 0 0; background: #BBE8F2; }
.B { height: 100%; background: #D9C666; }
扩展: line-height: height 有被问到该值是不是等于高度设置的值,这个没有答好,回来测试发现是跟盒模型相关的,需要是 computed height absolute + transform 居中为什么要使用 transform(为什么不使用marginLeft / Top),这是一道重绘重排的问题。 flex + align-items: center 我会对 flex 容器以及 flex 项目的每个 css 属性都了解一遍,并且写了一些小 demo, flex:1 代表什么