首页 > 解决方案 > 如何在滚动框中制作具有固定宽度但相对高度的元素

问题描述

我有一个里面<pre>有一个<code>块,其中可以扩展到一些max-height,之后会出现一个 scollbar。我希望添加一个:before,它将与<code>块内的内容具有相同的长度,但只有一些固定数量的像素宽。就上下文而言,我在我审核的 subreddit 的块中的行之前添加行号<code>(所以我只能使用 CSS),滥用content:属性和数字列表。这是我正在使用的精简版:

pre {
    max-height: 50px;
	border:1px solid #000000;
	z-index:1;
	position:relative;
    overflow: auto;
}
pre code{
	padding:0px 11px 0px 11px!important;
	margin-left:30px;
	display:block;
}

pre code:before{
	height: 100%;
	color:#FFF;
	position: absolute;
	left:-5px;
	width:30px;
	white-space:pre-wrap;
	direction:rtl;
	overflow:hidden;
	z-index:2;
	background:#369;
	left:0px;
	padding-right:5px;
	content:"1   2   3   4   5   6   7   8   9   10"
}
<pre>
<code>Line one
Line two
Line three
Line four
Line five
Line six
Line seven
</code>
</pre>

这很好用,除了当内容的长度超过:before时,出现在代码块左侧的 不会一直向下延伸,导致它创建一个滚动条。它仅在滚动框的可见大小处可见 - 而不是内容本身(在框内向下滚动)。我可以用 替换,但是数字远远超出了块的长度。<code>max-height<code>height: 100%height: auto<code>

如何使:before我创建的元素跨越滚动框内块的整个高度<code>,具有固定宽度(30px),仅使用 CSS?我也不能“硬编码”任何与 相同的值max-height,因为当用户将鼠标悬停在代码上时它会暂时增加。

标签: css

解决方案


添加相对于code而不是的位置pre

beforecodeposition absolute而您已将位置分配relativepre,其高度为 50px,即 的高度before仅为 50px。

因此,通过使代码相对,高度before变得等于code

pre code {
  padding: 0px 11px 0px 40px!important;
  /*margin-left: 30px;*/
  display: block;
  position:relative;
}

pre {
  max-height: 50px;
  border: 1px solid #000000;
  z-index: 1;
  /*position: relative;*/
  overflow: auto;
}

pre code {
  padding: 0px 11px 0px 40px!important;
  /*margin-left: 30px;*/
  display: block;
  position: relative;
}

pre code:before {
  height: 100%;
  color: #FFF;
  position: absolute;
  left: -5px;
  width: 30px;
  white-space: pre-wrap;
  direction: rtl;
  overflow: hidden;
  z-index: 2;
  background: #369;
  left: 0px;
  padding-right: 5px;
  content: "1   2   3   4   5   6   7   8   9   10"
}
<pre>
<code>Line one
Line two
Line three
Line four
Line five
Line six
Line seven
</code>
</pre>


推荐阅读