css居中布局的几种方式

一、水平居中

  • 若是行内元素,则直接给其父元素设置text-align: center即可
  • 若是块级元素,则直接给该元素设置margin: 0 auto即可
  • 若子元素包含浮动元素,则给父元素设置width:fit-content并且配合margin
.parent {
    width: -webkit-fit-content;
    width: -moz-fit-content;
    width: fit-content;
    margin: 0 auto;
}
  • 使用flex布局的方式,可以轻松实现水平居中,即使子元素中存在浮动元素也同样适用
// flex 2012年版本写法
.parent {
    display: flex;
    flex-direction: row;
    justify-content: center;
}

// flex 2009年版本写法
.parent {
    display: box;
    box-orient: horizontal;
    box-pack: center;
}
  • 使用绝对定位的方式,再配合CSS3新增的transform属性
.child {
    position: absolute;
    left: 50%;
    transform: translate(-50%, 0);
}
  • 使用绝对定位的方式,再配合left:0;right:0;margin:0 auto;(此方法需要固定宽度)
.child {
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 200px; // 假定宽度为200px
}

二、垂直居中

  • 若元素是单行文本,则直接给该元素设置line-height等于其父元素的高度
  • 若元素是行内块级元素,可以配合使用display:inline-block;vertical-align:middle和一个伪元素来让内容块居中
.parent::after, .child {
    display: inline-block;
    vertical-align: middle;
}

.parent::after {
    content: "";
    height: 100%;
}
  • 使用vertical-align属性并且配合使用display:tabledisplay:table-cell来让内容块居中
.parent {
    display: table;
}

.child {
    display: table-cell;
    vertical-align: middle;
}
  • 使用flex布局的方式,可以轻松实现垂直居中,即使子元素中存在浮动元素也同样适用
// flex 2012年版本写法
.parent {
    display: flex;
    align-items: center;
}

// flex 2009年版本写法
.parent {
    display: box;
    box-orient: vertical;
    box-pack: center;
}
  • 使用绝对定位的方式,再配合CSS3新增的transform属性
.child {
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);
}
  • 使用绝对定位的方式,再配合负值的margin-top(此方法需要固定高度)
.child {
    position: absolute;
    top: 50%;
    height: 200px; // 假定高度为200px
    margin-top: -100px; // 负值的绝对值为高度的一半
}
  • 使用绝对定位的方式,再配合top:0;bottom:0;margin:auto 0;(此方法需要固定高度)
.child {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto 0;
    height: 200px; // 假定高度为200px
}

三、水平垂直居中

  • 使用flex布局的方式同样可以轻松实现水平垂直居中
// flex 2012年版本写法
.parent {
    display: flex;
    justify-content: center;
    align-items: center;
}

// flex 2009年版本写法
.parent {
    display: box;
    box-pack: center;
    box-align: center;
}
  • 使用绝对定位的方式,再配合CSS3新增的transform属性
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
  • 使用绝对定位的方式,再配合使用负值的margin-top和负值的margin-left(此方法需要同时固定宽度和高度)
.child {
    position: absolute;
    left: 50%;
    top: 50%;
    margin-top: -50px; // 负值的绝对值为高度的一半
    margin-left: -100px; // 负值的绝对值为宽度的一半
    width: 200px; // 假定宽度为200px
    height: 100px; // 假定高度为100px
}
 

猜你喜欢

转载自www.cnblogs.com/chen-cheng/p/11949878.html