我已经研究了十多个与此类似的问题,但是我认为它们与我的情况都不足够相似。这不是我的确切设置,但我已对其进行了简化,以期使其更易于解释和回答。
我有3个div。如果窗口宽于600像素,则div1和div2应该正常流动,向左浮动,而div3应向右浮动。使用@media查询,如果窗口的宽度小于600像素,则div 3应该出现在div1和div2上方,向下推以使它们堆叠在一起。
我已经尝试了在所有3个div上使用display和position属性进行实验,但是我不知道该如何进行这项工作。我正在使用模板化系统,因此无法添加容器。我只能使用这3个div。
#id1 {
background: red;
width: 100px;
height: 100px;
}
#id2 {
background: yellow;
width: 100px;
height: 100px;
}
#id3 {
background: blue;
width: 100px;
height: 100px;
float: right;
position: fixed;
top: 50px;
right: 20px;
}
@media only screen and (max-width: 600px) {
#id3 {
float: left;
position: absolute;
top: 0px;
left: 0px;
}
}
<div id="id1">DIV 1</div>
<div id="id2">DIV 2</div>
<div id="id3">DIV 3</div>
答案 0 :(得分:1)
设置position: relative
并更正top
/ left
/ right
值:
#id1 {
background: red;
width: 100px;
height: 100px;
}
#id2 {
background: yellow;
width: 100px;
height: 100px;
}
#id3 {
background: blue;
width: 100px;
height: 100px;
float: right;
position: fixed;
top: 50px;
right: 20px;
}
@media only screen and (max-width: 600px) {
#id3 {
float: left;
position: relative;
top: 0;
left: 0;
right: unset;
}
}
<div id="id1">DIV 1</div>
<div id="id2">DIV 2</div>
<div id="id3">DIV 3</div>
要将div#id3
放在顶部,您需要使用position: absolute
并为所有3个div设置自定义顶部位置:
#id1 {
background: red;
width: 100px;
height: 100px;
}
#id2 {
background: yellow;
width: 100px;
height: 100px;
}
#id3 {
background: blue;
width: 100px;
height: 100px;
float: right;
position: fixed;
top: 50px;
right: 20px;
}
@media only screen and (max-width: 600px) {
#id1,
#id2,
#id3 {
position: absolute;
top: 10px;
float: none;
}
#id1{ top: 110px; }
#id2{ top: 210px; }
#id3{ right: unset; }
}
<div id="id1">DIV 1</div>
<div id="id2">DIV 2</div>
<div id="id3">DIV 3</div>
答案 1 :(得分:0)
请阅读https://developer.mozilla.org/en-US/docs/Web/CSS/order。 我希望这有帮助。如果您需要我向您解释,请告诉我。我会很高兴。
body {
display: flex;
/* Optional, if you want the DIVs 100% width: */
flex-direction: column;
}
#id1 {
background: red;
width: 100px;
height: 100px;
}
#id2 {
background: yellow;
width: 100px;
height: 100px;
}
#id3 {
background: blue;
width: 100px;
height: 100px;
float: right;
position: fixed;
top: 50px;
right: 20px;
}
@media only screen and (max-width: 600px) {
body > #id3 { order: 1; }
body > #id1 { order: 2; }
body > #id2 { order: 3; }
#id3 {
float: left;
position: relative;
top: 0px;
left: 0px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
<div id="id1">DIV 1</div>
<div id="id2">DIV 2</div>
<div id="id3">DIV 3</div>
</body>
</html>
这对我来说是最好的解决方法
答案 2 :(得分:0)
我只是想出了一个满足自己需求的完美解决方案。在@media查询中向div1添加一个margin-top
会使其颠簸并使其div2向下:
@media only screen and (max-width: 600px) {
#id3 {
float: left;
position: absolute;
top: 0px;
left: 0px;
}
#id1 {
margin-top: 100px;
}
}