优秀的编程知识分享平台

网站首页 > 技术文章 正文

CSS元素水平垂直居中的方式(css水平、垂直居中的写法,请至少写出4种?)

nanyue 2024-09-02 19:07:59 技术文章 5 ℃

1、已知子元素的高度和宽度,父元素相对定位,子元素绝对对定位。

 <div class="parent">
            <div class="child">子元素</div>
  </div>
.parent {
     border: 1px solid #888;
     width: 300px;
     height: 300px;
     padding: 20px;
     position: relative;
}
.child {
      background-color: #f40;
      width: 150px;
      height: 150px;
      position: absolute;
      left: calc(50% - 75px);
      top: calc(50% - 75px);
}

2、子元素的高度和宽度不知,父元素相对定位,子元素绝对定位,然后利用CSS3的transform属性。

.parent {
     border: 1px solid #888;
     width: 300px;
     height: 300px;
     padding: 20px;
     position: relative;
}
.child {
      background-color: #f40;
      position: absolute;
      transform: translateX(-50%) translateY(-50%);
  		left: 50%;
      top: 50%;
}

3、子元素的高度和宽度不知,利用flex布局。

.parent {
     border: 1px solid #888;
     width: 300px;
     height: 300px;
     padding: 20px;
     display: flex;
     align-items: center;
     justify-content: center;
}
.child {
      background-color: #f40;
}
最近发表
标签列表