Ruby's Louvre

每天学习一点点算法

导航

在td中实现overflow:hidden

工作中遇到的一个需要,但td是不支持overflow,总会被里面的元素撑大。注意,我所说的是元素,如果里面只是文本,我们可以使用white-space:pre;加overflow:hidden搞定这问题。

<!doctype html>
<html>
<head>
	<title>td内实现overflow:hidden</title>
	<style>
	table{  
		border:1px solid #a9ea00;
		border-collapse:collapse; 
		empty-cells:show;
	}
	td{
		border:1px solid #a9ea00;
		padding:0;
		height:20px;
		width:140px;
		overflow:hidden;
	}
	td div{
		width:180px;
 		height:70px;
 		background:red;
	}
</style>
</head>

<body>
<h1>直接使用在td中使用overflow</h1>
<table>
	<tr>
		<td><div>司徒正美司徒正美司徒正美司徒正美</div></td>
		<td>2</td>
		<td>3</td>
	</tr>
	<tr>
		<td>4</td>
		<td>5</td>
		<td>6</td>
	</tr>
</table>


</body>
</html>

对于这个问题,普通的做法的是在里面再套一个与td同样大小的div,设置其为overflow:hidden。这意味着我们必要要知道td的大小才行!这对于自适应布局的表格有点不利,虽然实在不行时,我们还可以动用到javascript。

<!doctype html>
<html>
<head>
	<title>td内实现overflow:hidden</title>
	<style>
	table{  
		border:1px solid #a9ea00;
		border-collapse:collapse; 
		empty-cells:show;
	}
	td{
		border:1px solid #a9ea00;
		padding:0;
		height:20px;
		width:140px;
		overflow:hidden;
		
	}
    td div{
		width:140px;
 		height:20px;
 		background:green;
	}
	td div div{
		width:180px;
 		height:70px;
 		background:red;
	}
</style>
</head>

<body>
<h1>在td再套一个div</h1>
<table>
	<tr>
		<td><div><div>司徒正美司徒正美司徒正美司徒正美</div></div></td>
		<td>2</td>
		<td>3</td>
	</tr>
	<tr>
		<td>4</td>
		<td>5</td>
		<td>6</td>
	</tr>
</table>


</body>
</html>

除此以外,还有没有更好的办法呢?

posted on 2010-09-08 22:58  司徒正美  阅读(4907)  评论(4)    收藏  举报