如何在div中对齐span元素? [重复]

时间:2022-11-25 14:22:49

This question already has an answer here:

这个问题在这里已有答案:

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:如何在div中对齐span元素? [重复]

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>