这四个CSS属性样式用于定位对象盒子,必须定义position属性值为absolute或者relative此取值方可生效。

一、语法结构

Left、right、top、bottom后跟数字+html单位。

示范结构

div{left:20px}

div{right:20px}

div{top:20px}

div{bottom:20px}

Left 靠左距离多少

Right 靠右边距离多少

Top 距离顶部距离多少

Bottom距离下边距离多少

二、使用条件

通常单独使用left、right、top、bottom均无效,需要在使用绝对定位CSS position样式才能生效。

一般left和right在一个样式是只能使用其一,不能left和right都设置,要么使用left就不使用right,要么使用right就不使用left,如果left和right均使用将会出现兼容问题,一个对象设置了靠左left多少距离,自然右边距离自然就有了所以无需设置左边。

相同道理,top和bottom对一个对象只能使用其一,不然会出现逻辑兼容问题。譬如一个人让你往左走,一个人让你往右走,同时发出往左往右走这个时候你也不好判断往那边走。

三、绝对定位中使用

一般left、right、top、bottom使用于配合position定位对象位置。大家可以进入CSS position教程篇了解学习这些样式属性。

实例:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>无标题文档</title> 
<script type="text/javascript" language="javascript"> 
function selA(id) { 
switch(id) { 
case "1": 
document.getElementById("subobj").style.position = "static"; 
break; 
case "2": 
document.getElementById("subobj").style.position = "absolute"; 
break; 
case "3": 
document.getElementById("subobj").style.position = "relative"; 
break; 
case "4": 
document.getElementById("subobj").style.position = "fixed"; 
break; 
} 
} 
</script> 
<style type="text/css"> 
#all { 
  width:190px; 
  height:95px; 
  padding:10px 0 0 10px; 
  border:1px #000 solid; 
  position:relative; 
} 
#subobj { 
  width:100px; 
  height:50px; 
  border:1px #000 solid; 
  bottom:9px; 
  position:static; 
} 
#sel { 
  margin-top:5px; 
} 
select { 
  width:200px; 
} 
</style> 
</head> 
<body> 
<div id="all"> 
<div id="subobj">子对象1</div> 
</div> 
<div id="sel"><select onchange="selA(this.value)"><option value="1">static</option><option value="2">absolute</option><option value="3">relative</option><option value="4">fixed</option></select></div> 
</body> 
</html>
登录后复制

以上就是有关css left right top bottom定位的介绍与实例展示的详细内容,更多请关注Work网其它相关文章!

09-17 00:11