首页  >  文章  >  web前端  >  如何垂直对齐 a 内部?

如何垂直对齐 a 内部?

Linda Hamilton
Linda Hamilton原创
2024-10-28 02:22:01521浏览

How to Vertically Align a  Inside a ?

对齐 垂直在

考虑以下情况:您有一个 嵌套在

中,如以下代码所示:
<div 
  id="theMainDiv"
  style="
    border:solid 1px gray;
    cursor:text;
    width:400px;
    padding:0px;"
>
  <span 
    id="tag1_outer" 
    style="
      background:#e2e6f0;
      padding-right:4px;
      padding-left:4px;
      border:solid 1px #9daccc;
      font:normal 11px arial;
      color:#3c3c3c"
  >as</span>
</div>

默认情况下,将与

的左下角对齐。将 居中在
内垂直方向,请考虑以下方法:

选项 1:行高操作

设置子元素 的行高等于

的高度。
#theMainDiv {
  height: 20px; /* Set the div height for reference */
}

#tag1_outer {
  line-height: 20px;
}

选项 2:绝对定位

应用绝对定位容器。然后,将子项 定位到绝对位于顶部:50% 并使用 margin-top:-YYYpx,其中 YYY 代表子项已知高度的一半。
#theMainDiv {
  position: relative; /* Apply relative positioning to the div */
}

#tag1_outer {
  position: absolute;
  top: 50%;
  margin-top: -10px; /* Half the height of the child span */
}

请参阅提供的有关理解垂直对齐的文章以了解更多详细信息和其他技术.

以上是如何垂直对齐 a 内部?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn