This question already has an answer here:
这个问题在这里已有答案:
- How to vertically center a <span> inside a div? [duplicate] 5 answers
如何在div内垂直居中? [重复] 5个答案
UPDATE about duplicated question: it is not the same question since I can not set the height of the containter div.
关于重复问题的更新:这不是同一个问题,因为我无法设置容器div的高度。
How to horizontally and vertically align a span element inside a div.
如何在div内水平和垂直对齐span元素。
The div is resposive element, so it can takes several sizes. The span has not set height nor the width
div是resposive元素,因此它可能需要几种尺寸。跨度没有设置高度和宽度
<div class="the-div">
<span class="the-span" >span here</span>
</div>
I tried with:
我尝试过:
.the-span{top: 50%; text-align: center}
I don't want to use js for this.
我不想为此使用js。
Capture:
1 个解决方案
#1
You can transform its position thusly:
你可以这样改变它的位置:
html,
body {
width: 100%;
height: 100%;
}
div,
span {
width: 50%;
height: 50%;
border: 1px solid;
display: block;
position: relative;
}
span {
transform: translateY(-50%) translateX(-50%); /* <--offset top/left by half its own height/width */
left: 50%; /* position half way within containing div */
top: 50%; /* position half way within containing div */
}
<div>
<span>
</span>
</div>
#1
You can transform its position thusly:
你可以这样改变它的位置:
html,
body {
width: 100%;
height: 100%;
}
div,
span {
width: 50%;
height: 50%;
border: 1px solid;
display: block;
position: relative;
}
span {
transform: translateY(-50%) translateX(-50%); /* <--offset top/left by half its own height/width */
left: 50%; /* position half way within containing div */
top: 50%; /* position half way within containing div */
}
<div>
<span>
</span>
</div>