以下标记扩展了容器div(其中包含我想显示的背景图像),但对齐左侧的框:
.HTML:
<div class="container">
<div class="box"></div>
</div>
.CSS
.container{
background-image:url('image.png');
width:100%;
}
.box{
width:100px;
height:100px
}
如果我在盒子上使用float:right
或position:absolute;right:0px;
,它会向右对齐,但容器div 不会展开以适合盒子。
有没有办法将框对齐到屏幕右侧,同时让容器展开以适应?感谢您的阅读。
float:right
; 在盒子上就可以了,只需在容器上也添加overflow:auto
即可。
下面的示例,将边框添加到框中以提高可见性:
.container {
background-image:url('http://www.placehold.it/100x100');
width:100%;
overflow:auto;
}
.box {
width:100px;
height:100px;
border:1px solid red;
float:right;
}
<div class="container">
<div class="box"></div>
</div>
使用浮点数时,您需要对容器使用 clearfix:
.container:after {
content: "";
display: table;
clear: both;
}
并像您:)一样将盒子漂浮起来
这是为了强制容器识别浮动内容。clearfix 是元素自动清除其子元素的一种方式,因此您无需添加其他标记。它通常用于浮动布局。
示例:http://jsfiddle.net/v3r3p5cs/
此方法将有助于支持IE 8及更高版本的浏览器以及所有现代浏览器
如果您需要较少的 IE8 支持,因为较旧的浏览器不支持空内容,您可以使用:
.clearfix:after {
content: " ";
visibility: hidden;
display: block;
height: 0;
clear: both;
}