佈局:元素水平居中的方法


前提

//body是類似這樣的形式
<body>
	<div class="father">
        <div class="son">

        </div>
    </div>
</body>

1. 彈性盒子

第一種

		.father{
            width: 200px;
            height: 200px;
            background-color: green;
            display: flex;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: khaki;
            margin: auto auto;
        }

第二種

		.father{
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            align-content: center;
            background-color: salmon;
            width: 200px;
            height: 200px;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: skyblue;
        }

第三種

		.father{
            width: 200px;
            height: 200px;
            background-color: yellow;

            display: flex;
            justify-content: center;
            align-items: center;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: black;
        }

2. 定位加位移

		.father{
            width: 200px;
            height: 200px;
            background-color: #7aff9b;
            position: relative;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: #EEEEEE;

            position: absolute;
            top:50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }

3. Margin

		.father{
            width: 200px;
            height: 200px;
            position: relative;
            background-color: #0086ff;
        }
        .son{
            width: 100px;
            height: 100px;
            background-color: green;
            position: absolute;
            
            /*這裏的left、right、top、bottom必須寫*/
            margin: auto auto;
            left: 0;
            right: 0;
            top:0;
            bottom: 0;
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章