[英]make two inner boxes vertically aligned center in the effective way?
.dd{ height:100px; width:100%; border:1px soild red; background:#000; } .dd .d1{ height:20px; width:20px; border:1px solid green; display:inline-block; } .dd .d2{ height:20px; width:20px; border:1px solid green; display:inline-block; } .dd .d3{ height:40px; width:30px; border:1px solid yellow; display:inline-block; }
<div class="dd"> <div class="d1"></div> <div class="d2"></div> <div class="d3"></div> </div>
在我的項目中,我始終找不到垂直元素的好方法。 任何人都有使元素(任何環境)垂直對齊的優點?
我自己的愚蠢方式:
當out div沒有高度時,對我來說更容易,我經常使頁邊距的頂部與頁邊距的底部對齊,並且將其垂直對齊,如下所示:
.dd{ height:auto; width:100%; background:#000; } .dd>div:first-child{ display:inline-block; margin-top:1em; margin-bottom:1em; height:80px; width:50px; border:1px solid red; margin-left:1em; } .dd>div:last-child{ display:inline-block; margin-top:1em; margin-bottom:1em; height:50px; width:50px; border:1px solid green; }
<div class="dd"> <div></div> <div></div> </div>
但是在這種情況下,我暫時找不到好的做法,有人知道嗎?
第二添加
而且我改變了我的愚蠢方式:
.dd>div:first-child{height:50px }
至
.dd>div:first-child{height:80px }
似乎我的愚蠢方法確實可行,除非您將height:80px更改回height:50px
請在這里進行更多說明,以便我們能理解它為什么可以工作,謝謝
嘗試使用此:
.dd {
display: flex;
align-items: center;
}
這樣,.dd容器中的所有項目都將垂直居中。 如果您還希望所有內容都水平居中,請輸入:
justify-content: center;
編輯注意:盡管如此,它在flex容器內的元素高度仍然有效。
根據本文檔 ,在CSS2中,您可以使用table-cell
顯示和vertical-align
屬性,但是我不太喜歡這種代碼。
這是使用該代碼的小提琴: https : //jsfiddle.net/Laf2wv4n/1/
我已經使用:pseudo
element :before
parent :before
的dd
來垂直對齊內部元素
每個內聯元素都可以使用vertical-align:middle
我使用了偽元素,因此可以用作height
為父元素100%
的inline-block
元素
.dd { height: 100px; width: 100%; border: 1px soild red; background: #000; } /* added to vertiaclly align the elements inside */ .dd:before { content: ''; height: 100%; /* set the height of the element to 100% so that the inner elements can align to its full height */ display: inline-block; /* this is the property which is need to vertically center */ width: 1px; /* set the width to 1px */ margin-left: -1px; /* so that the width doesnt effect the children */ vertical-align: middle; /* is added to vertically align the elements */ } .dd div { vertical-align: middle; /* is added to vertically align the elements */ } /* end */ .dd .d1 { height: 20px; width: 20px; border: 1px solid green; display: inline-block; } .dd .d2 { height: 20px; width: 20px; border: 1px solid green; display: inline-block; } .dd .d3 { height: 40px; width: 30px; border: 1px solid yellow; display: inline-block; }
<div class="dd"> <div class="d1"></div> <div class="d2"></div> <div class="d3"></div> </div>
垂直對齊文本或塊是非常古老且已知的html / css問題。 經過多年的發展,提出了許多解決方案,這些解決方案取決於瀏覽器的功能和初始條件(文本或塊,元素的已知或不高度等)。
克里斯·科耶爾(Chris Coyier)嘗試將所有技術收集在其自己的網站上的完整指南中,並按最常用的用例進行分類。
目前,我最喜歡的是最現代的方法: flexbox
和通過transform: translateY(-50%)
對齊transform: translateY(-50%)
規則。 它們最簡潔明了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.