」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何垂直對齊 a 內部?

如何垂直對齊 a 內部?

發佈於2024-11-09
瀏覽:333

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:絕對定位

將絕對定位應用於

容器。然後,將子級 絕對定位在 top: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 */
}

請參閱所提供的有關理解垂直對齊的文章,以了解更多詳細資訊和其他技術。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3