css两种居中方式对比

本文介绍了两种使用CSS实现元素居中的方法:一种是利用position属性使元素固定在页面中心,即使页面滚动也能保持居中;另一种是通过margin:auto实现普通居中,但随滚动条滚动。文中提供了具体的HTML和CSS代码示例。

1.浮动始终上下左右居中

<html>
	<head>
		<title></title>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	</head>
	<style type="text/css">
	body{
		background: yellow;
		padding:0;
		margin: 0;
	}
		#fixed-div{
			width: 200px;
			height: 200px;
			background: slateblue;
			position: fixed;
    		margin:auto;
    		left:0; 
    		right:0; 
    		top:0; 
    		bottom:0;
		}
		
	</style>
	<body>
			<div id="fixed-div">
				浮动居中
			</div>
			
	</body>
</html>

效果如下

滚动条下拉依然上下左右居中

left:0;和right:0;控制左右居中        不需要左右居中可以移除这两个

同理上下居中也是一个道理

2.普通居中  会随着滚动条运动而变化位置

<html>
	<head>
		<title></title>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
	</head>
	<style type="text/css">
	body{
		background: yellow;
		padding:0;
		margin: 0;
	}
		#center-div{
			width: 200px;
			height: 200px;
			background: slateblue;
			margin: auto;
		}
		
	</style>
	<body>
			<div id="center-div">
				居中
			</div>
		
			
	</body>
</html>

效果图如上  滚动条滚动就会随着一起运动 显示不完全


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值