width: 500px; border: 1px solid black; } #first { width: 300px; border: 1px solid red; } #second { border: 1px solid green; } <div id="wrapper"> <div id="first">Stack Overflow is for professional and enthusiast programmers, people who write code because they love it.</div> <div id="second">When you post a new question, other users will almost immediately see it and try to provide good answers. This often happens in a matter of minutes, so be sure to check back frequently when your question is still new for the best response.</div> </div>
我希望两个div在包装div中彼此相邻。在这种情况下,绿色div的高度应确定包装纸的高度。
我如何通过CSS实现呢?
浮动一个或两个内部div。
浮动一格:
#wrapper { width: 500px; border: 1px solid black; overflow: hidden; /* will contain if #first is longer than #second */ } #first { width: 300px; float:left; /* add this */ border: 1px solid red; } #second { border: 1px solid green; overflow: hidden; /* if you don't want #second to wrap below #first */ }
或者如果您同时浮动两个子元素,则需要鼓励包装器div包含两个浮动子元素,否则它会认为它是空的而不是在它们周围放置边框
浮动两个div:
#wrapper { width: 500px; border: 1px solid black; overflow: hidden; /* add this to contain floated children */ } #first { width: 300px; float:left; /* add this */ border: 1px solid red; } #second { border: 1px solid green; float: left; /* add this */ }