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>

  • 异位妊娠的处理办法
  • 京酱肉丝的做法
  • DNF如何免费解除虚弱
  • 手机咕咚软件APP怎么退出登录
  • 航海日记副官招募攻略
  • 热门搜索
    去韩国旅游必买 狼牙山旅游景点 米亚罗旅游攻略 红色旅游论文 去澳大利亚旅游费用 英国旅游签证新政策 朝鲜旅游见闻 兰州旅游网 澳大利亚旅游地图 阿里巴巴旅游