CSS中确定绝对元素大小的两种方法

Absolute Sizing 任何使用CSS已有一段时间的人都会知道绝对和相对定位的优点。 回顾一下:

position: relative允许元素从其原始位置水平(使用leftright )或垂直位置(使用topbottom )移动。

position: absolute允许使用leftrighttopbottom相对于包含块定位元素(包含块是具有相对,绝对或固定位置的最近祖先节点)。

因此,定位节点很简单,例如

HTML:


<div id="outer">
	<div id="inner"></div>
</div>

CSS:


#outer
{
	position: relative;
	width: 200px;
	height: 200px;
	margin: 20px auto;
	border: 2px solid #c00;
}

#inner
{
	position: absolute;
	left: 50px;
	top: 50px;
	width: 96px;
	height: 96px;
	background-color: #ddc;
	border: 2px solid #00c;
}

(由于添加了边框,内部块的实际宽度和高度将为100px)。

在每个现代浏览器(包括IE6)中都会呈现以下框:

少为人知的是,你可以将所有的leftrighttopbottom同时性能。 以下CSS将相同地渲染内部元素:


#inner
{
	position: absolute;
	left: 50px;
	right: 50px;
	top: 50px;
	bottom: 50px;
	background-color: #ddc;
	border: 2px solid #00c;
}

内部框的宽度和高度将保持100px,但是我们不需要显式设置尺寸。

在以下情况下,这可能会很有用:

  • 元素周围的间距比宽度或高度更重要。 您还可以使用负的leftrighttop和/或bottom属性使内部框大于其外部父级。
  • 您有多个具有不同边框和填充的内部元素,但需要一致的外部间距。 此方法使您可以为所有这些元素创建一个样式。

JavaScript动画也可以从中受益,因为如果不需要计算结果的宽度和高度,例如,调整元素的大小可以更加轻松快捷地进行调整,例如


// expands and contracts the inner box
window.onload = function() {

	var inner = document.getElementById("inner");
	var offset = 100, dir = -1;
	setInterval(function() {
		inner.style.left = inner.style.right = inner.style.top = inner.style.bottom = offset+"px";
		offset += dir;
		if (offset == 0 || offset == 100) dir = -dir;
	}, 10);
	
}

关于浏览器兼容性的注意事项:该技术在所有主要浏览器中都适用, IE6 除外, IE6仅了解显式的宽度和高度。 有惊喜!

From: https://www.sitepoint.com/css-sizing-absolute-position/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值