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

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

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

HTML

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

CSS

.divstyle {
    width: 200px;
    height: 50px;
    background-color: grey;
}

我通过javascript创建完整的DIV:

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

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

+-----------------+
| TEXT            |
+-----------------+

我希望是这样的:

TEXT
+-----------------+
|                 |
+-----------------+

我尝试的内容:

.divstyle::before {
    top: -50px;
    left: -20px;
}

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

pxyaymoc

pxyaymoc1#

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

div {
  display: inline-grid;
  grid-auto-rows: 1fr;
}

div:after {
  content: '';
  border: dashed 1px;
}
<div>TEXT</div>
bweufnob

bweufnob2#

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

<div class="divstyle"></div>
.divstyle {
    width: 200px;
    height: 50px;
    background-color: grey;
    position: relative;
    margin-top: 50px;
}

.divstyle::before{
    content: 'TEXT';
    position: absolute;
    top: -50%;
}

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

r9f1avp5

r9f1avp53#

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

<div class="divstyle">
    <span class="textstyle">
        TEXT
    </span>
</div>

看起来就像这样

.textstyle {
        position: absolute;
        top: -20px;
        font-size: 24px;
    }

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

lndjwyie

lndjwyie4#

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

<div class="divstyle">
  <span class="out">TEXT</span>
</div>

CSS

.divstyle {
  position: relative;
  background-color: grey;
}
.out {
  position: relative;
  top: -1em;
}

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

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

CSS

.divstyle {
  background-color: grey;
}
.divstyle:before {
  content: attr(content);
  position: absolute;
  top: -1em;
}

相关问题