一、定位(Positioning)

1.1 相对定位

.img-container {
  position: relative;
  width: 300px;
  height: 200px;
}

.img-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

1.2 绝对定位

.img-container {
  position: relative;
  width: 300px;
  height: 200px;
}

.img-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

二、混合定位(Mixing Positioning)

混合定位可以结合使用 position: relativeposition: absolute,以实现更灵活的布局。

.img-container {
  position: relative;
  width: 300px;
  height: 200px;
}

.img-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  padding: 10px;
}

三、Flexbox

.img-container {
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('image.jpg');
  background-size: cover;
}

.img-overlay {
  text-align: center;
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  padding: 10px;
}

四、Grid

.img-container {
  display: grid;
  place-items: center;
  background-image: url('image.jpg');
  background-size: cover;
}

.img-overlay {
  text-align: center;
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  padding: 10px;
}

五、伪元素

.img-container::before {
  content: '这是一段文字';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(255, 255, 255, 0.5);
  color: #333;
  font-size: 24px;
  padding: 10px;
}

总结