将文本与文本的中心对齐作为参考点
问题描述:
我有一些文字,我尝试在图表上的移动刻度下对齐。我可以得到它做与蜱坚持:将文本与文本的中心对齐作为参考点
<div class="foo">Text</div>
.foo {
width: $tick-location px;
text-align: right;
}
但问题是,这始终对齐,使文本的末端接触蜱。我真正想要的是触摸滴答的文字中心。然而,我并没有提前知道文本的大小。
我该如何做到这一点?
例子:
----------|-----
xxxxx
----------|-----
xxxxx
首先是我目前得到的。第二是我想要的。
答
使用变换进行文本居中。更好改变left
,而不是改变的 'width'
.foo {
position:relative;
display: inline-block;
width: auto;
left:100px;
/* here text's center will be at 100px; */
/* left:$tick-location px; */
transform:translateX(-50%);
}
<div class="foo">Text</div>
答
可以存在用于此JavaScript溶液。 https://jsfiddle.net/wingsofwind/mxspevy0/
var b = $(".longerdiv").html().length;
var a = $(".foo").html().length;
$(".foo").offset({
left: b * 3.02
});
.foo {
width: 20 px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="longerdiv">------------|------</div>
<div class="foo">Text</div>
答
我创建的你想什么样。希望这会起作用。
var e = document.getElementById("animatedElement");
var s = 1;
var timer = setInterval(function(){
var ePosition = e.offsetLeft;
e.style.left = (ePosition + 10) + 'px';
}, 1000);
setTimeout(() => { clearInterval(timer); }, 45000);
.foo {
width: 50px;
text-align: center;
border-top:5px solid #000;
}
#animatedElement {
position: absolute;
top: 5px;
left: 10px;
width: 25px;
height: 25px;
background: red;
}
.mainDiv{
width:500px;
height:200px;
background-color:#e8dbff;
border:2px solid #000;
}
.divWithTick{
width: 50px;
height:30px;
background-color:#fff;
}
.tick{
width:2%;
height:30px;
background-color:blue;
margin:0 auto;
}
<div class="mainDiv">
<div id="animatedElement">
<div class="divWithTick">
<div class="tick"></div>
</div>
<div class="foo">
Text
</div>
</div>
</div>
您可以添加图片显示你正在尝试做什么? – Chaitanya
'$ tick-location',尝试在PHP中的东西? – NoobEditor
不,我只是把它放在那里作为读者的标记。实际上它是直接在HTML模板中设置的Angular Dart变量。 –