居中定位css

<div class="parent">
<div class="item"></div>
</div>

  1. 已知元素的寬度和高度:
    .item {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -75px;
    margin-left: -75px;
    }
    .item {
    position: absolute;
    margin:auto;
    left:0;
    top:0;
    right:0;
    bottom:0;
    }

  2. 未知元素的高度和寬度:
    .item {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); / 使用css3的transform來實現 /
    }
    .parent {
    display: flex;
    justify-content:center;
    align-items: center;
    background: #AAA;
    height: 300px; / 注意這裏需要設置高度來查看垂直居中效果 /
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章