创建具有重叠文本的图块布局 - 负边距是错误的方法吗?

时间:2016-03-08 04:03:56

标签: css

我试图创建一个基本的平铺布局,文本通过负边距覆盖每个平铺。



.tile{float:left; margin-bottom:185px;}

.tile img{width:280px; height:290px; margin-right:5px; border:1px solid black;  }

h1{margin-top:-150px; background:rgba(0,0,0,.5); color:white; position:relative; max-width:280px;}

<div class="tile" id="tile1">
	<img src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Las_vegas_late_60s.png" />
	<h1><span>Hello world</span><h1>
</div>

<div class="tile" id="tile2">
<img src="https://upload.wikimedia.org/wikipedia/commons/5/54/Red_Rock_Canyon_National_Conservation_Area_-_Blue_Diamond%2C_Nevada.jpg" />
<h1><span>Goodbye world</span><h1>
</div>

<div class="tile" id="tile3">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/cf/Las_Vegas_seal.svg/212px-Las_Vegas_seal.svg.png" />
<h1><span>Hello world</span><h1>
</div>

<div class="tile" id="tile4">
<img src="https://upload.wikimedia.org/wikipedia/commons/2/20/Photo_3974341-1500x1000-1.jpg" />
<h1><span>Hello world</span><h1>
</div>
&#13;
&#13;
&#13;

不幸的是,在某些浏览器窗口大小下,负边距会导致其他图块重叠。但是,如果我调整特定窗口大小的负边距,那么在其他窗口大小之前我会遇到问题:

enter image description here

enter image description here

这个问题的解决方案是什么?

1 个答案:

答案 0 :(得分:1)

.tile {
  display: inline-block;
  position: relative;
  width: 280px;
  margin-right: 5px;
  margin-bottom: 5px;
}
.tile img {
  width: 100%;
  height: 290px;
  border: 1px solid black;
}
h1 {
  position: absolute;
  top: 150px;
  left: 1px;
  width: 100%;
  background: rgba(0, 0, 0, .5);
  color: white;
}
<div class="tile" id="tile1">
  <img src="https://upload.wikimedia.org/wikipedia/commons/2/2c/Las_vegas_late_60s.png" />
  <h1><span>Hello world</span><h1>
</div><div class="tile" id="tile2">
<img src="https://upload.wikimedia.org/wikipedia/commons/5/54/Red_Rock_Canyon_National_Conservation_Area_-_Blue_Diamond%2C_Nevada.jpg" />
<h1><span>Goodbye world</span><h1>
</div><div class="tile" id="tile3">
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/c/cf/Las_Vegas_seal.svg/212px-Las_Vegas_seal.svg.png" />
<h1><span>Hello world</span><h1>
</div><div class="tile" id="tile4">
<img src="https://upload.wikimedia.org/wikipedia/commons/2/20/Photo_3974341-1500x1000-1.jpg" />
<h1><span>Hello world</span><h1>
</div>