javascript 将文本垂直移动到容器外部

zbdgwd5y  于 2023-05-27  发布在  Java
关注(0)|答案(4)|浏览(199)

我有一些CSS样式和DIV内的文本DIV。如何将TEXT移出DIV并使用CSS或JavaScript应用一些样式?

HTML

  1. <div class="divstyle">TEXT</div>

CSS

  1. .divstyle {
  2. width: 200px;
  3. height: 50px;
  4. background-color: grey;
  5. }

我通过javascript创建完整的DIV:

  1. var inputfield = document.createElement("div");
  2. inputfield.textContent = inputfieldData['TEXT'];
  3. inputfield.classList.add("divstyle");
  4. inputfieldsContainer.appendChild(inputfield);

在浏览器中呈现时,它看起来像这样:

  1. +-----------------+
  2. | TEXT |
  3. +-----------------+

我希望是这样的:

  1. TEXT
  2. +-----------------+
  3. | |
  4. +-----------------+

我尝试的内容:

  1. .divstyle::before {
  2. top: -50px;
  3. left: -20px;
  4. }

有没有办法只使用CSS在DIV中添加DIV?也许解决方案可以是将TEXT Package 在一些标签中并对其应用CSS,但如果可以通过CSS来实现呢?

pxyaymoc

pxyaymoc1#

不完全清楚你想要什么,也许像这样的东西会适合你:

  1. div {
  2. display: inline-grid;
  3. grid-auto-rows: 1fr;
  4. }
  5. div:after {
  6. content: '';
  7. border: dashed 1px;
  8. }
  1. <div>TEXT</div>
bweufnob

bweufnob2#

您可以将伪元素的内容设置为'TEXT',而不是在div中设置文本,并执行以下操作。

  1. <div class="divstyle"></div>
  2. .divstyle {
  3. width: 200px;
  4. height: 50px;
  5. background-color: grey;
  6. position: relative;
  7. margin-top: 50px;
  8. }
  9. .divstyle::before{
  10. content: 'TEXT';
  11. position: absolute;
  12. top: -50%;
  13. }

https://codepen.io/caglar62/pen/LYgaPPW

展开查看全部
r9f1avp5

r9f1avp53#

您可以使用其他样式添加范围(此处:textstyle)

  1. <div class="divstyle">
  2. <span class="textstyle">
  3. TEXT
  4. </span>
  5. </div>

看起来就像这样

  1. .textstyle {
  2. position: absolute;
  3. top: -20px;
  4. font-size: 24px;
  5. }

这里要注意的重要部分是position被设置为absolute,因此可以相对于其第一个定位的祖先元素来定位它。

展开查看全部
lndjwyie

lndjwyie4#

虽然我不明白你为什么要这样做,但这里有两种方法可以实现它:
1.第一种方式:
HTML

  1. <div class="divstyle">
  2. <span class="out">TEXT</span>
  3. </div>

CSS

  1. .divstyle {
  2. position: relative;
  3. background-color: grey;
  4. }
  5. .out {
  6. position: relative;
  7. top: -1em;
  8. }

2/第二种方式(在阅读您的第一条评论后):
HTML

  1. <div class="divstyle" content="TEXT">&nbsp;</div>

CSS

  1. .divstyle {
  2. background-color: grey;
  3. }
  4. .divstyle:before {
  5. content: attr(content);
  6. position: absolute;
  7. top: -1em;
  8. }
展开查看全部

相关问题