带子div的div的背景颜色 [英] Background color for div with child divs

查看:143
本文介绍了带子div的div的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<html>
<head>
<style type="text/css">
div
{
background-color:#ccc;
}
</style>
</head>

<body>
<div>
<div style="float: left;">This is a text inside a div element.</div>
<div style="float: right;">We are still in the div element.</div>
</div>

</body>
</html>

为什么在这2个div之间没有显示背景色?

Why isnt the background color showing up in between those 2 divs?

推荐答案

浮动元素时,应提供浮动元素的宽度.否则,您可能会在不同的浏览器中遇到意外行为.

When you float elements you should provide the width of the floated elements. Otherwise you may encounter unexpected behaviors accross different browsers.

查看本教程,有关在CSS中进行浮动的详细信息. [链接已死]

Check this tutorial, there is good info on floating in css. [link is dead]

基本上,如果为容器div提供overflow:hidden;并为浮动元素提供宽度,则将解决您的问题.

Basically, if you provide an overflow:hidden; to the container div and provide width to the floated elements, your problem will be solved.

<div style="overflow: hidden;">
  <div style="float:left; width: 300px;">Some text</div>
  <div style="float:right; width: 300px;">Some text</div>
</div>

类似地,您可以在要标准化流的任何地方添加另一个div,例如:

Similarly, you can add another div wherever you want to normalize the flow ike this:

<div>
  <div style="float:left; width: 300px;">Some text</div>
  <div style="float:right; width: 300px;">Some text</div>
  <div style="clear:both;"></div>
  <div>This div will be at the same place 
       as if the previous elements are not floated</div>
</div>

两者都可以工作:)

编辑

这些天我经常使用的另一种方法是浮起第一个元素,并为随后的元素设置一个margin-left.例如:

Another method which I use frequently in these days is to float the first element and set a margin-left to the following element. For instance:

<div>
    <div style="float: left; width: 300px;">Some text</div>
    <div style="margin-left: 300px;">Some text</div>
    <div style="clear: both;"></div>
</div>

此方法的优点在于,后面的元素(在这种情况下为第二个div)不需要固定的宽度.另外,您可以跳过第三格(clear: both;).它是可选的.我只是添加它以防浮动div的高度大于第二个div的高度,因为如果不添加它,则父div将始终获得第二个div的高度.

The advantage of this method is that the following element (the second div in this case) does not need a fixed width. Plus, you may skip the third div (clear: both;). It's optional. I just add it in case that the floated div is longer in height than the second div since if you don't add it the parent div will always get the height of the second div.

这篇关于带子div的div的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆