css 上下左右居中的三种方法

时间:2026-02-13 19:54:57

1、方法一:中心点定位(已知盒子大小)

<html>

<head>

<style>

html,body{

width: 100%; height: 100%;

}

body{

width: 1px; position: relative; left: 50%; top: 50%; height: 1px;

}

.wrap{

position: absolute; left: -300px; top: -200px; width: 600px; height: 400px; background: #000;

}

</style>

</head>

<body>

<div class="wrap"></div>

</body>

<html>

2、方法二:上下左右(已知盒子大小)

<html>

<head>

<style>

html,body{

width: 100%; height: 100%;

}

.wrap{

position: absolute; left: 0; right: 0; top: 0; bottom: 0; width: 600px; height: 400px; margin: auto; background: #000;

}

</style>

</head>

<body>

<div class="wrap"></div>

</body>

<html>

3、方法三:css transform(盒子大小可自适应)

<html>

<head>

<style>

html,body{

width: 100%; height: 100%;

}

.wrap{

position: relative; left: 50%; top: 50%; width: 600px; height: auto; background: #000; transform:translate(-50%,-50%); color: #fff;

font-size: 20px; line-height: 35px;

  }

</style>

</head>

<body>

<div class="wrap">

壬戌之秋,七月既望,苏子与客泛舟游于赤壁之下。清风徐来,水波不兴。举酒属客,诵明月之诗,歌窈窕之章。少焉,月出于东山之上,徘徊于斗牛之间。白露横江,水光接天。纵一苇之所如,凌万顷之茫然。浩浩乎如冯虚御风,而不知其所止;飘飘乎如遗世独立,羽化而登仙。

</div>

</body>

<html>

© 2026 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com