<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>常见元素布局</title>
<style type="text/css">
/* 1、水平居中布局 */
/* 1.单个元素水平居中 宽度不固定 缺点:须要涉及到父类的样式*/ .content { text-align: center;
} .box { display: inline-block; color: #fff; background: #0000FF;
}
</style>
</head>
<body>
<div class="content">
<div class="box"> 宽度不固定 </div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>常见元素布局</title>
<style type="text/css">
/* 1、水平居中布局 */
/* 2.单个元素水平居中 宽度不固定 缺点:设置为表格元素,内部元素的布局有可能受到影响*/ .box { display: table; margin: 0 auto; background: #ff9933; color: #fff; /* background和color测试更好的观看效果 */
}
</style>
</head>
<body>
<div class="content">
<div class="box"> 宽度不固定 </div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>常见元素布局</title>
<style type="text/css">
/* 1、水平居中布局 */
/* 3.单个元素水平居中 宽度不固定 缺点:transform,兼容性较差*/ .content { position: relative;
} .box { position: absolute; left: 50%; transform: translateX(-50%); background: #ff9933; color: #fff; /* background和color测试更好的观看效果 */
}
</style>
</head>
<body>
<div class="content">
<div class="box"> 宽度不固定 </div>
</div>
</body>
</html>
效果:css