CSS-居中布局

html 结构:

DEMO

css代码:

  • 水平居中
  1. inline-block + text-align
.parent{
    text-align: center;
}
.child{
    display: inline-block;
}
  1. table + margin
.child{
    display: table;
    margin: 0 auto;
}
  1. absolute + transform
.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}
  1. flex + justify-content / margin
.parent{
    display: flex;
    justify-content: center;
}
.child{
    margin: 0 auto;
}
  • 垂直居中
  1. table-cell + vertical-align
.parent{    
    display: table-cell;
    vertical-align: middle;
}
  1. absolute + transform
.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    transform: translateY(-50%);
}
  1. flex + align-items
.parent{
    display: flex;
    align-items: center;
}
  • 水平居中 + 垂直居中
  1. inline-block + text-align + table-cell + vertical-align
.parent{
    text-align: center;
    display: table-cell;
    vertical-align: middle;
}
.child{
    display: inline-block;
}
  1. absolute + transform
.parent{
    position: relative;
}
.child{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
  1. flex + justify-content
.parent{
    display: flex;
    justify-content: center;
    align-items: center;
}

你可能感兴趣的:(CSS-居中布局)