CSS:如何更好地在div边框上叠加图像?

4
我有一个带实线边框的div,想要在其上方叠加一个居中的Logo。
目前我有一个解决方案,只需将图像嵌入页面,然后使用'margin-top:-13px;text-align:center;'将其移动到位置。

https://jsfiddle.net/christophera/43Ljmoh9/

.inside-article {
  margin-top:20px;
  border-top-style: solid;
  border-top-width: 5px;
  border-top-color: red;
}
.pos-logo {
  margin-top:-13px;
  text-align:center;
  }

<div class="inside-article">
<div class="pos-logo">
<img style="width:120px;"  src="https://test.consumer.press/img/consumer-press.svg" />
</div>
</div>

我已经在Chrome和Edge桌面版本上进行了测试,它可以正常工作... 我需要使用@media来调整margin-top以使其在我的手机上正常工作... 但是...这是一个好的方法吗?还是你有更好的方法?
谢谢,
Chris
4个回答

0

您可以使用伪元素来创建边框,而且它是100%响应式的。

将其位置设置为绝对定位,并使用top:50%保持在中间,使用transform:translateY(-50%)将其位置居中,并设置z-index:-1以置于图层后面。

Make sure to set vertical-align: middle for the img so that it stays in mid line

.inside-article {
  margin-top:20px;
  position: relative;
}
.inside-article::before {
  content: '';
  border-top-style: solid;
  border-top-width: 5px;
  border-top-color: red;
  position: absolute;
  left: 0;
  width: 100%;
  top: 50%;
  transform: translateY(-50%);
  z-index: -1;
}
.pos-logo {
  text-align:center;
  }
  img{vertical-align: middle;}
<div class="inside-article">
<div class="pos-logo">
<img style="width:120px;"  src="https://test.consumer.press/img/consumer-press.svg" />
</div>
</div>


0
如果您在容器中使用display:flex,则无论图像的尺寸如何,都可以将其居中放置在其中心。
在图像容器上使用:before 伪选择器来绘制线条,并使用百分比绝对定位 - 这意味着如果您的div更改其高度,则该线条也始终位于中心。

.inside-article {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.inside-article .pos-logo img {
  display: block;
  width: 120px;
}

.inside-article .pos-logo:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  border-top: 5px solid red;
  width: 100%;
  transform: translateY(-50%);
  z-index: -1;
}
<div class="inside-article">
  <div class="pos-logo">
    <img src="https://test.consumer.press/img/consumer-press.svg" />
  </div>
</div>


0

当您使用<fieldset><legend>元素时,这变得非常简单。

.inside-article {
  border: none;
  border-top: 5px solid red;
}

.pos-logo {
  margin: auto;
}

.logo-image {
  width: 120px;
}
<fieldset class="inside-article">
  <legend class="pos-logo">
    <img class="logo-image" src="https://test.consumer.press/img/consumer-press.svg" />
  </legend>
</fieldset>

注意: fieldset 元素是为表单元素和标签而设计的,因此如果您真的需要符合标准,不建议使用此解决方案。

但这段代码是最短的,这也是值得一提的 :)


谢谢,我考虑过这个方案,但是我正在使用一个wp模板,并且尽量不更改HTML。我喜欢这个想法,正在调查和测试其他解决方案。 - Chris

0

你可以将 margin-top: -13px 直接替换为 transform: translateY(-50%);,这样就能得到完全相同的结果,而且不需要计算负像素。


我在网站上尝试了这些解决方案中的每一个。这是最简单的一个,而且在实践中效果最好,不会干扰其他任何东西。感谢大家对此提供不同的答案和看法! - Chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接