内层元素(如img图片)相对于外层容器绝对水平居中的实现方法(pure CSS)

:若外层容器比其内的图片元素的更宽的话,只需要一个text-align即可实现图片的水平居中,要是外层容器比子元素还窄,里层子元素想居中肿么办???


其实原理很简单,只需要一个万能计算公式:left=(width1-width2)/2                                                                         注:width1:外层容器的宽度,width2:内层元素的宽度

即设置内层元素距离外层容器左侧的值为二者的宽度之差的1/2;(ofcause 我们不会真的写js去计算宽度啦^-^)


先看下效果图:

width1 > width2

width1 < width2

上代码:

width1 > width2:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title> New Document </title>
    <style>
	  div#content {
		position:absolute;
		top:0;right:0;bottom:0;left:0;
		margin:auto;
		width:500px;
		height:300px;
		background-color:yellow;
	  }
	  
	  div#content1 {
		overflow:visible;
		position:relative;
		float:left;
		left:50%;
	  }

	  div img {
		  position:relative;
		  float:left;
		  left:-50%;
	  }
    </style>
 </head>
 <body>
	<div id="content">
		<div id="content1">
			<img src="5.jpg">
		</div>
	</div>
 </body>
</html>

<span style="font-weight: bold;">      width1 < width2:</span>

<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title> New Document </title>
    <style>
	  div#content {
		position:absolute;
		top:0;right:0;bottom:0;left:0;
		margin:auto;
		width:250px;
		height:300px;
		overflow: visible;
		background-color:yellow;
	  }
	  
	  div#content1 {
		overflow:visible;
		position:relative;
		float:left;
		left:50%;
	  }

	  div img {
		  position:relative;
		  float:left;
		  left:-50%;
	  }
    </style>
 </head>
 <body>
	<div id="content">
		<div id="content1">
			<img src="5.jpg">
		</div>
	</div>
 </body>
</html>
兼容各个浏览器哦~(没有IE6故没测~)

最后啰嗦一下:上边的万能公式:left=(width1-width2)/2 = width1/2 - width2/2,  用css表示就是:left:50%  and left:-50%

再允许我上两张拙劣的图:




ok~



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值