如何为div中的每个元素设置float,而不为每个元素指定float?

时间:2010-01-13 04:54:46

标签: css xhtml

如何为div中的每个元素设置float?

我想将float赋予内部元素,而不是父DIV?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #000; font: 16px Helvetica, Arial; color: #fff; }
div {border:2px solid red;height:50px}
a {border:2px solid blue;margin:10px}
</style>
</head>
<body>

<div>
<a>Hello from JS Bin</a>
  <a>from JS Bin</a>
  </div>
</body>
</html>

2 个答案:

答案 0 :(得分:14)

您可以使用*选择器定位元素的所有子元素,因此在您的示例中,您可以添加:

div * { float: right; }

请注意,这会浮动所有孩子和他们的孩子,所以如果你有嵌套内容,它可能不是你想要的,在这种情况下你可能想要:

div > * { float: right; }

但是,> direct descendant selector isn't supported in older versions of IE(可能还有其他浏览器?)。

答案 1 :(得分:10)

继续下面的Alconja是绕过后代选择器问题的好方法:

div *{ float: right; } 
div * *{ float: none; }

这将使一切正常,然后一切的孩子将被重置为无。