我有一个包装器和两个元素:left div和right div。左div仅包含可能很长的文本。右边div包含异步加载的图像,我们不知道它的宽度:
<div id="wrapper">
<div id="left">TEXT TEXT TEXT TEXT</div>
<div id="right">IMAGE</div>
</div>
我想以这种方式显示所有内容:
+-----------------------------+ | | | #wrapper | | | | +----------+ +--------+ | | | | | | | | | #left | | #right | | | | | | | | | +----------+ +--------+ | | | +-----------------------------+
为此,我准备了这个CSS:
#wrapper{
width: 600px;
display: inline-block;
}
#left{
float: left;
width: 400px;
}
#right{
float: left;
width: 200px;
}
现在我想添加一些响应此布局。左div的最小宽度应该是200px,所以如果右边的图像宽度大于400px,它应该转到下一行,并且div应该以这种方式增长到100%的包装器:
+-----------------------------+ | | | #wrapper | | | | +----------------------+ | | | | | | | #left | | | | | | | +----------------------+ | | | | +--------------+ | | | | | | | #right | | | | | | | +--------------+ | | | +-----------------------------+
如何在不使用JavaScript的情况下执行此操作?
我找到了这个解决方案:http://jsfiddle.net/fxWg7/1865/并且我需要的唯一区别是当左div为小时,则右div应该转到下一行而不是左div。
它应该是这样的:
#left.width = #wrapper.width - #right.width;
if (#left.width < 200px) {
#left.width = 100%;
#right move to new line;
} else {
display #left div on left side and #right div next to #left div
}
答案 0 :(得分:0)
我向你的div添加了float:left,请参阅http://jsfiddle.net/fxWg7/1866/
#wrapper {
height: auto;
overflow: hidden;
}
#right {
width: auto;
float: right;
background: #aafed6;
}
#left {
float: left;
background: #e8f6fe;
width: auto;
overflow: hidden;
min-width: 200px;
max-width:300px;
}
答案 1 :(得分:0)
我已经创建了一个带有一些突出显示的CSS来回答您的问题:http://jsfiddle.net/ericnjanga/kexn9ys6/。 如果它适合您,请告诉我。
/* Mobile first:
1) We apply no widths to #wrapper, #left and #right,
they are divs and span 100% naturally.
2) The #left which has a higher position in the DOM will naturally be on top
*/
#wrapper{
overflow: auto; /*helps contains floating children*/
}
#left{}
#right{}
/*
Mobile viewport only: We apply a "max-width: 100%" to "#right img" in order to maintain
its natural width as long as the layout is wider but, to make it fit
if the layout gets smaller */
@media (max-width: 599px) {
#right img{
/* maintain img natural width as long as the layout is wider but
spans 100% when the layout gets smaller */
max-width : 100%;
}
}
/* Higher viewports:
After that breaking point, set the wrapper width and make sure the right image scales up and down with the layout */
@media (min-width: 600px) {
#wrapper{
margin: 0 auto; /* centers all elements on the page */
width: 600px;
}
/* It is better to set #left and #right widths in % */
#left{
float: left;
width: 60%;
}
#right{
float: left;
width: 40%;
}
#right img{
width: 100%;
height: inherit;
}
}