使用负边距%将元素彼此堆叠

时间:2019-03-18 17:13:19

标签: html css

在尝试使这些行显示为堆叠并占据父级的整个宽度时,但是某些东西在偏移后续行,因此只有第一行(与底部对齐)可以正确显示:

.sp-line{
  display: inline-block;
  width: 100%;
  margin-right: -100%;
  position: relative;
  z-index: 10;
  border-top: 1px dotted #000;
}
.sp_baseline{
  border-color: blue;
  vertical-align: baseline;
}
.sp_text-bottom{
  border-color: green;
  vertical-align: text-bottom;
}
.sp_bottom{
  border-color: red;
  vertical-align: bottom;
}
.sp_text-top{
  border-color: green;
  vertical-align: text-top;
}
.line{
  border: 1px solid cyan;
}

span.text {
  background-color: papayawhip;
  line-height: 1.96; 
}
<div class="line">
  <span class="sp-line sp_bottom"></span>
  <span class="sp-line sp_baseline"></span>
  <span class="sp-line sp_text-bottom"></span>
  <span class="sp-line sp_text-top"></span>
  <span class="text1 text">SINGLE line</span>
</div>

试图到达:

enter image description here

我只是想从https://christopheraue.net/design/vertical-align重新创建这些行,所以看不到这里缺少的内容。

2 个答案:

答案 0 :(得分:1)

无需制作元素width:100%并使用负边距。取而代之的是,您可以使元素较小以将它们放在一行中,然后依靠溢出使虚线覆盖所有区域:

.line {
  overflow-x:hidden;
}

.sp-line{
  display: inline-block;
  width: 2px;
  position: relative;
  z-index: 10;
}
.sp-line:before {
  content:"";
  position:absolute;
  border-top: 1px dotted;
  bottom:0;
  left:-100vw; /*big value here*/
  right:-100vw;/*big value here*/
}
.sp_baseline{
  color: blue;
  vertical-align: baseline;
}
.sp_text-bottom{
  color: green;
  vertical-align: text-bottom;
}
.sp_bottom{
  color: purple;
  vertical-align: bottom;
}
.sp_top{
  color: red;
  vertical-align: top;
  transform:translateY(1px); /*we move the top one by 1px so we can see it*/
}
.sp_text-top{
  color: green;
  vertical-align: text-top;
}

span.text {
  background-color: papayawhip;
  line-height: 1.96; 
  font-size:40px;
}
<div class="line">
  <span class="text1 text">SINGLE line</span>
  <span class="sp-line sp_bottom"></span>
  <span class="sp-line sp_top"></span>
  <span class="sp-line sp_baseline"></span>
  <span class="sp-line sp_text-bottom"></span>
  <span class="sp-line sp_text-top"></span>
</div>

答案 1 :(得分:1)

我相信您遇到的问题与sp类的100%宽度有关。它需要考虑.line类(青色轮廓)上的边框以及字体上的一些间距。我已设置宽度以将其计算为100%减去4px来满足此要求:

.sp-line {
  display: inline-block;
  width: calc(100% - 4px);
  margin-right: -100%;
  position: relative;
  z-index: 10;
  border-top: 1px dotted #000;
}

.sp_baseline {
  border-color: blue;
  vertical-align: baseline;
}

.sp_text-bottom {
  border-color: green;
  vertical-align: text-bottom;
}

.sp_bottom {
  border-color: red;
  vertical-align: bottom;
}

.sp_text-top {
  border-color: green;
  vertical-align: text-top;
}

.line {
  border: 1px solid cyan;
}

span.text {
  background-color: papayawhip;
  line-height: 1.96;
}
<div class="line">
  <span class="sp-line sp_bottom"></span>
  <span class="sp-line sp_baseline"></span>
  <span class="sp-line sp_text-bottom"></span>
  <span class="sp-line sp_text-top"></span>
  <span class="text1 text">SINGLE line</span>
</div>