首頁  >  文章  >  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