两个边框重叠不同的大小

问题描述 投票:3回答:3

是否有更好的方法来设置两个边框,如下例所示?我只能通过定位来做到这一点。我是新来的,所以我为任何错误道歉。

.border1 {
  margin: 0 auto;
  height: 300px;
  width: 250px;
  border: 9px solid red;
  position: relative;  
}

.border2 {
  border: 9px solid blue;
  height: 250px;
  width: 300px;
  position: absolute;
  top: 12px;
  left: -33px;
}
<div class="border1">
  <div class="border2"></div>
</div>
html css
3个回答
4
投票

绝对确实是一个好的,简单的方法。

您还可以使用伪坐标和仅坐标来调整第二个边框的大小。

.border1 {
  margin: 0 auto;
min-height: 150px;/* allow it to grow */
  width: 250px;
  padding:20px 0.5em;
  border: 9px solid red;
  position: relative;
}

.border2:before {
content:'';
  border: 9px solid blue;
pointer-events:none;/* to allow clicking through else you may use a negative z-index */
  position: absolute;
  top: 12px;
bottom:12px;
  left: -33px;
right:-33px;
}
<div class="border1 border2">
add anything here instead setting height
</div>

0
投票

这是一种不同的方法。我使用box-shadow作为第二个边框,你将不再需要第二个div作为第二个边框。

.border{
   margin:0 auto;
   height:300px;
   width:250px;
   border:9px solid red;
   position:relative; 
   box-shadow: 0 0 0px 9px blue;
  }
<div class="border"></div>

0
投票

您可以使用Flexbox执行此操作,无需进行不必要的计算:

.border1 {
  margin: 0 auto;
  height: 300px;
  width: 250px;
  border: 9px solid red;
  display: flex; /* displays flex-items (children) inline */
  justify-content: center; /* centers them horizontally */
  align-items: center; /* and vertically */
}
  
.border2 {
  flex: 0 0 300px; /* doesn't shrink, flex-basis set to "300px" (initial width) */
  border: 9px solid blue;
  height: 250px;
}
<div class="border1">
  <div class="border2"></div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.