讓內容垂直居中,是一個很重要的應用情景,在很多場合都會需要。這也是面試的時候,一些考官喜歡拿來初面的小題目。
這里,小結下讓內容垂直居中的三種方式。
當然,讀者如果有更好的方法,也可以提出來。
基本HTML:
<div class="big"><div class="small"></div>
</div>
基本CSS:
.big{width: 600px;height: 400px;background: #eee;
}
.small{width: 200px;height: 150px;background: #f00;
}
一、使用flex
.big{display: flex;justify-content: center;align-items: center;
}
二、使用grid
.big{display: grid;place-items:center;
}
.big{display: grid;
}
.small{place-self: center;
}
三、使用position
.big{position: relative;
}
.small{position: absolute;left:50%;top:50%;transform: translate(-50%,-50%);
}