CSS 水平垂直居中
生活随笔
收集整理的這篇文章主要介紹了
CSS 水平垂直居中
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
方法一:
容器確定寬高:知識點(diǎn):transform只能設(shè)置在display為block的元素上。
<head><meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
#container{
width: 500px; /* 確定!*/
height: 300px;
background-color: pink;
}
#child{
width: 100px; /* 如果沒有寬度,div充滿容器,怎么水平居中 */
position: relative; /* 相對父容器進(jìn)行定位,規(guī)定top left值 */
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 如果不設(shè)置這個,其實(shí)是子div的左上原點(diǎn)是水平垂直居中,這個translate百分比是自身的百分比*/
text-align: center; /* 里面的文字居中 */
}
</style>
</head>
<body>
<div id="container">
<div id="child">哈哈哈哈</div>
</div>
</body>
方法一效果圖:
方法二:
利用 flex 布局實(shí)際使用時(shí)應(yīng)考慮兼容性,flex不兼容ie9父容器高度沒有設(shè)置,那么其高度就是子容器撐開的,也就沒有垂直居中這一說,只需要水平居中即可。
.container { display: flex; align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */} .container div { width: 100px; height: 100px; background-color: pink; /* 方便看效果 */}
?
本文轉(zhuǎn)載于:猿2048https://www.mk2048.com/blog/blog.php?id=hji0a2j&title=CSS 水平垂直居中
總結(jié)
以上是生活随笔為你收集整理的CSS 水平垂直居中的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Markdown 进阶
- 下一篇: CSS3景深-perspective