如何在 pre 标签内制作右对齐的内部元素

How to make right aligned inner element inside a pre tag

我有一个问题只能通过 CSS/Query 解决 - HTML 更改是不可能的,因为 HTML 在网站上的数千个页面上实现。

截图(一)

如果宽度较小,它可以正常工作,但是当滚动条可见时,我将其向右移动以查看代码,然后 "COPY" 按钮也向左移动,

截图(2)

我使用脚本添加了复制按钮,它可以很好地处理数千页。无法解决问题。

HTML:

<pre class="i3-code">
--example code--
</pre>

脚本:

 <script type="text/javascript">
    function cpy(t){var e=t.innerText,n=document.createElement("textarea");n.setAttribute("class","invisible"),n.setAttribute("id","cpytxtbox"),n.textContent=e,document.body.append(n),n.select(),document.execCommand("copy"),document.getElementById("cpytxtbox").outerHTML=""}var $input=$('<div class="copy-btn"><input type="button" value="Copy"/></div>');$input.prependTo($(".i3-code")),$(".copy-btn").click(function(){cpy(this.parentElement)});
  </script>

CSS:

.i3-code {
    background-color: #fefbed;
    font-size: 1em;
    line-height: 1.2;
}
.copy-btn {
    text-align: right;
    margin-left: -8px;
    margin-right: -8px;
    margin-top: -8px;
    margin-bottom: 5px;
    background-color: #f4f4f4;
}
.copy-btn input {
    background: #e1e1e1;
    color: #000;
    border: none;
    font-weight: 500;
    padding: 7px;
    transition: background 1s;
}

可以使用此 URL(在任何示例代码上)通过调整 window 屏幕

的大小来完成实时测试
https://www.includehelp.com/python/date-toordinal-method-with-example.aspx

这应该可以解决问题:

.copy-btn {
    text-align: right;
    margin-left: -8px;
    margin-right: -8px;
    margin-top: -8px;
    margin-bottom: 5px;
    background-color: #f4f4f4;
    position: sticky;
    top: -8px;
    left: -8px;
    right: -8px;
    overflow: hidden;
}

它实现了position: sticky

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to- 
 fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" 
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" 
  integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" 
  crossorigin="anonymous">
  </head>
  <body>
<pre class="float-right position-sticky">
</pre>




  </body>
</html>