簡體   English   中英

垂直對齊固定定位div內的跨度

[英]Vertically aligning span inside fixed positioned div

我知道,之前有關於這方面的帖子,但是我已經查看了所有這些帖子,但似乎仍然無法使其工作。 我見過的大多數相關答案都要求你指定包含div的高度,在我的例子中是動態的。

我在窗口底部有一個固定的div。 我希望在右側有一個關閉按鈕,並且無論高度如何,總是在div的中心垂直對齊。

JSfiddle: https ://jsfiddle.net/w2zd3q0b/1/

 .bottombar { width: 100%; position: fixed; left: 0; bottom: 0; z-index: 9990; border: 1px solid #000; padding: 0.5em; } .bottombar p { /* Leave room for the dismiss button */ margin: 0 1.5em 0 0; padding: 0; } .dismiss { position: absolute; right: 1.5em; cursor: pointer; } 
 <div class="bottombar"> <p>This is some message inside of a div. I want to vertically center align the span. This is some message inside of a div. I want to vertically center align the span.<span class="dismiss">X</span></p> </div><!--/.bottombar --> 

在這種情況下,它看起來很好,直bottombar div占用多行文本,然后跨度不再垂直居中。

您可以使用適用於未知高度容器的CSS3 transform

.dismiss {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  ...
}

 .bottombar { width: 100%; position: fixed; left: 0; bottom: 0; z-index: 9990; border: 1px solid #000; padding: 0.5em; box-sizing: border-box; } .bottombar p { margin: 0 1.5em 0 0; padding: 0; } .dismiss { position: absolute; top: 50%; transform: translateY(-50%); right: .5em; cursor: pointer; } 
 <div class="bottombar"> <p>This is some message inside of a div. I want to vertically center align the span. This is some message inside of a div. I want to vertically center align the span. <span class="dismiss">X</span></p> </div> 

我還在代碼片段中為div添加了box-sizing ,以便為您提供真正的100%寬度(包括邊框),您可能需要稍微調整相關間距。

DEMO

在此輸入圖像描述

所以我清理了一些東西,並使用flexbox以簡單的樣式flexbox (更多信息在這里

.bottombar {
    width:100%;
    position: fixed;
    left: 0;
  bottom: 0;
    z-index: 9990;
  border: 1px solid #000;
  /* padding: 0.5em; */
  display: flex;
  align-items: center;
}
.bottombar>span {
  padding: 0.5em;
}
.bottombar .message{
  flex-grow: 1;
}

.dismiss {
    cursor: pointer;
}

HTML

<div class="bottombar">
    <span class='message'>
         This is some message inside of a div. I want to vertically center align the span.
    </span>
    <span class="dismiss">X</span>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM