天马行空的CSS(四)


CSS

布局

常见的布局 demo
预览链接

浮动布局,flex 布局,flex 和负 margin 布局定宽或者使用 calc 不定宽等方式基本能实现大多数的布局,在搭配绝对定位等可以实现几乎所有布局

常见居中方式

css-tricks总结了各种居中的方式可以参考

水平居中

/* 内联元素 适用于在块级的父元素中水平放置内联元素   */
.parent {
  text-align: center;
}
/* 块级元素 可以加宽度(width:100px;)或者改变 display(display:table;) .parent { */
  margin: 0 auto;
}
/* 多个块级元素 子元素设置 inline-block,同时父元素设置 text-align:center */
.parent {
  text-align: center;
}
.child {
  display: inline-block;
}

垂直居中

/* 单行的内联元素 设置上下 padding 相同  */
.child {
  padding: 20px 0;
}
/* 设置行高等于高度  */
.chind {
  line-height: 100px;
  height: 100px;
}
/* 多行的内联元素通过设置父元素table,子元素table-cell和vertical-align
vertical-align:middle的意思是把元素放在父元素的中部 */
.parent {
  display: table;
}
.child {
  display: table-cell;
  vertical-align: middle;
}
/* 已知高度的块级元素 利用 position 和 top 和负 margin, */
.parent {
  position: relative;
  height: 300px;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px;
}
/* 利用 position 和 top/bottom 和 margin:auto  */
.parent {
  position: relative;
  height: 300px;
}
.child {
  height: 100px;
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto;
}
/* 未知高度的块级元素 利用 position 和 top 和 transform  */
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

水平垂直居中

/* flex 大法好 */

.parent{
display:flex;
justify-content:center;
align-items:center;
}
/* 综合以上水平或者垂直居中的方法 */

/* 绝对定位+margin:auto */

.child{
width:100px;
height:100px;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
/* 绝对定位和负 margin */

.child{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%
margin-left:-50px;
margin-top: -50px;
}
/* 绝对定位和 transform */

.child {
position: absolute;
top: 50%;
left:50%
transform: translate(-50%,-50%);
}
/* table-cell */

.child{
display:table-cell;
text-align:center;
vertical-align: middle;
}
grid 布局暂时不用

文章作者: 沐雪
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 沐雪 !
评论
 上一篇
我知道的JS-数据类型 我知道的JS-数据类型
前言 原创之处并不优秀,优秀之处并非原创.良好 JavaScript 基础是前端工程师的赖以生存的基石,有了扎实的 js 基础才能走得更远.目前我的学习资料有:JavaScript 高级程序设计,阮一峰的 js 教程,你不知道的 JavaS
2018-04-04
下一篇 
天马行空的CSS(三) 天马行空的CSS(三)
CSS动画css 动画一般分为三种1、transition 补间动画2、keyframe 关键帧动画3、animation 逐帧动画 补间动画1、位置-平移(left/right/margin/transform)2、方位-旋转(tra
2018-03-15
  目录