【CSS】居中相關問題

CSS居中

居中是面試題中經常問到的問題,下面儘量總結記錄一番
內容提要:塊級元素的垂直水平居中
1.flex; 2.絕對定位+偏移:偏移有三種方法a.margin;b.calc();c.transform;

一、行內元素

1. 水平居中

	/* 所有inline相關的元素 */
	text-align: center;

2. 垂直居中

  • 單行
  1. 相等的padding-top和padding-bottom
  2. line-height等於height
  • 多行

vertical-align: middle;

二、塊級元素

1. 水平居中

margin: 0 auto;
水平居中

<body>
    <div class="box">
        <div class="content">center</div>
    </div>
    <style>
        body *{
            border: 1px red solid;
        }
        .box{
            background: #c9c9c9;
			/* 父元素有寬高 */
            width: 500px;
            height: 500px;
        }
        .content{
			/* 元素本身要有寬度 */
            margin: 0 auto;
            width: 100px;
			/* 內部文字水平居中 */
			height: 100px;
			text-align: center;
			/* 文字垂直居中 */
			line-height: 100px;
        }
    </style>
</body>

2. 水平垂直居中

2.1 絕對定位+偏移

通過absolute定位

<body>
    <div class="box">
        <div class="content">center</div>
    </div>
    <style>
        body *{
            border: 1px red solid;
        }
        .box{
            background: #c9c9c9;
            width: 500px;
            height: 500px;
			/* 父元素一定要設置相對 */
            position: relative;
        }
        .content{
            width: 100px;
            height: 100px;
            /* 文字垂直居中 */
            line-height: 100px;
            /* 文字水平居中 */
            text-align: center;
            position: absolute;
            /* 偏移 */
            left: 50%;
            top: 50%;
			/* 具體的偏移代碼 */
        }
    </style>
</body>

利用margin偏移(需要知道寬高)

    margin-top: -50px;
    margin-left: -50px;

利用calc偏移(需要知道寬高)

	top: calc(50% - 50px);
	left: calc(50% - 50px);

利用transform偏移(不需要寬高)

    transform: translate(-50%, -50%);

2.2 flex佈局

.box{
	display: flex;
	justify-content: center;
	align-items: center;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章