我需要实现类似的东西..
-------------------------
| |
| |
|---- dynamic text --- |
| |
-------------------------
我想要围绕"动态文字"在css。
我尝试在css之后使用& :: before和& ::但是当动态文本发生变化时我仍需要拉伸/减少那个。有什么想法吗?
答案 0 :(得分:1)
您可以使用JavaScript动态设置:before
和:after
:伪元素的宽度。
function foo() {
var ss = document.styleSheets;
var text = document.getElementById('text');
var box = document.getElementById('box');
var totalWidth = getComputedStyle(box).width.slice(0, -2);
var textWidth = text.offsetWidth;
var lineWidth;
var margin = 4; // Set the margin between text and line.
for (i = 0; i < ss.length; i++) {
var rules = ss[i];
for (j = 0; j < rules.cssRules.length; j++) {
var r = rules.cssRules[j];
if (r.selectorText == "#text:before") {
// If you want the margin to be set on both sides of the line,
// replace 'margin' with '(margin * 2)' in the next line.
lineWidth = ((totalWidth / 2) - (textWidth / 2) - margin);
r.style.width = lineWidth + 'px';
r.style.left = -(lineWidth + margin) + 'px';
} else if (r.selectorText == "#text:after") {
r.style.width = lineWidth + 'px';
r.style.right = -(lineWidth + margin) + 'px';
}
}
}
}
foo();
#box {
width: 300px;
height: 200px;
background-color: #FF0000;
line-height: 200px;
text-align: center;
}
#text {
position: relative;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
padding: 4px;
color: white;
}
#text:before {
content: "";
position: absolute;
border-bottom: 1px solid black;
height: 100px;
}
#text:after {
content: "";
position: absolute;
border-bottom: 1px solid black;
height: 100px;
}
<div id="box"><span id="text">This is the text which is dynamic</span>
</div>
答案 1 :(得分:0)
<div id="divWithBackground">
<div id="divActsAsLine">
<span id="DynamicText">Your text here </span>
</div>
</div>
现在的CSS
#divActsAsLine{
border-botton:1px solid #00;
text-align:center;
}
#DynamicText{
position:relative;
background-color: #fff;
margin-bottom:-20px /*Adjust this based on your requirements*/
z-index:1 /* optional */
}
逻辑是将div边距作为背景线并使跨度与此线重叠,为此,我们需要减少或增加margin属性。您可能需要在必要时使用z-index