【问题标题】:Relative position of picture as background in flex boxflex box中图片作为背景的相对位置
【发布时间】:2017-06-14 09:52:53
【问题描述】:

我想在不继承子框的容器中制作不透明的图像作为背景。

我的代码:

body{
	background-color: black;
	color: white;
	font-size: 30px;
	text-align: center;
	justify-content: center;
}
.container{
	border-color: white;
	border-style: solid;
	border-width: 2px;
    display: flex;
	width: 300px;
	min-height: 300px;
	justify-content: center;
	flex-direction: column;		
}
.box{
	opacity: 0.2;
	border-color: white;
	border-style: solid;
	border-width: 2px;
	flex: 1;
}
.box1{background-color: yellow;}
.box2{background-color: green;}
.box3{background-color: blue;}
.box4{background-color: red;}
.box5{background-color: orange;}

.container img{
  width: 100%;
  opacity: 0.3;
}
<body>
<div class="container">
	<img src="http://www.tapeciarnia.pl/tapety/normalne/191848_swiecace_kule_grafika_3d.jpg" alt=""> 
	<div class="box box1">Box 1</div>
	<div class="box box2">Box 2</div>
	<div class="box box3">Box 3</div>
	<div class="box box4">Box 4</div>
	<div class="box box5">Box 5</div>
</div>
	
</body>

我想将这些彩色框放在该图像上,但是当我尝试使用 position: relative;z-index: -1; 来图像和 position: absolute; 到框时,弹性定位不起作用。

您能否解释一下为什么 flex box 不适用于绝对定位并给出该问题的解决方案?

【问题讨论】:

  • 我对盒子使用不透明度只是为了在它们正确移动时查看背景图像,所以它是临时的

标签: css background position flexbox absolute


【解决方案1】:

当您将position: relative 设置为.container 并将position: absolute 设置为.container img 时,它似乎工作正常。

body{
	background-color: black;
	color: white;
	font-size: 30px;
	text-align: center;
	justify-content: center;
}
.container{
	border-color: white;
	border-style: solid;
	border-width: 2px;
    display: flex;
	width: 300px;
	min-height: 300px;
	justify-content: center;
	flex-direction: column;	
  position: relative;
}
.box{
	opacity: 0.2;
	border-color: white;
	border-style: solid;
	border-width: 2px;
	flex: 1;
}
.box1{background-color: yellow;}
.box2{background-color: green;}
.box3{background-color: blue;}
.box4{background-color: red;}
.box5{background-color: orange;}

.container img{
  position: absolute;
  width: 100%;
  opacity: 0.3;
}
<body>
<div class="container">
	<img src="http://www.tapeciarnia.pl/tapety/normalne/191848_swiecace_kule_grafika_3d.jpg" alt=""> 
	<div class="box box1">Box 1</div>
	<div class="box box2">Box 2</div>
	<div class="box box3">Box 3</div>
	<div class="box box4">Box 4</div>
	<div class="box box5">Box 5</div>
</div>
	
</body>

我认为 flexbox 不适用于绝对定位的元素,因为这些元素会创建新的块格式化上下文:BFC link

【讨论】:

  • 非常感谢!唯一的问题是图像不适合容器,但我已经通过试错法做到了:) 当我将position: absolute 放入容器、position: relative; 放入盒子并将position: absolute; 放入图像时,它运行良好。您关于绝对定位在弹性框中的问题原因的回答确实有帮助;D
【解决方案2】:

我通过将position: absolute; 放入容器并将图像上的position: relative; 更改为position: absolute; 并将盒子上的position: absolute; 更改为position: relative; 来修复我的代码。

好吧,看来我对位置属性还不够了解。所以我会很感激,如果有人可以回答,为什么它以前不起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 2011-08-11
    • 2014-08-23
    相关资源
    最近更新 更多