[英]Absolute vertical and horizontal center text in responsive div
我真的很想解決這個問題-我試圖在懸停在圖像上方的響應div中垂直和水平地顯示文本。
這是基本的HTML和CSS結構的jsfiddle 。
我嘗試了許多不同的CSS方法-使用table
(由於使用absolute
使文本位於圖像上方,因此無法使用, transform: translate(-50%, -50%); top: 50%; left: 50%;
這可以抵消文字以及目前我不記得的其他文字。
主要問題是我有兩個“圖層”-文字和下方的圖像。 為此,我需要使用absolute
,這會導致table
選項無法正常工作。
非常感謝您提出的任何建議。
注意:我使用的圖像必須保留16:9的寬高比。
謝謝!
.work{
display:table;
}
.work a{
position:relative;display:table;
}
.work h1{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
margin:0;
width:80%;
text-align:center;
}
.work img{
width:800px;
height:450px;
display:block;
max-width:100%;
}
發布CSS代碼,以純CSS為中心將水平和/或垂直對象居中(改編自我的responsive.css
腳本)。 包括對在線資源的引用。 根據需要使用。 請注意 ,在某些情況下,您可能需要稍微調整html結構以包含包裝器(請參見注釋)
/* center alignment classes */
/* http://www.dev-metal.com/center-div-vertically-horizontally-modern-method-without-fixed-size/ */
.center-vertical-wrapper
{
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;
}
.center-horizontal-wrapper
{
margin: 0;
padding: 0;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.center-h
{
margin-left: auto;
margin-right: auto;
}
.center-contents-h
{
text-align: center;
}
/* http://coding.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/#Height */
.center-absolute /* needs width/height to be set */
{
position: absolute;
bottom: 0;
left: 0;
top: 0;
right: 0;
float:left;
margin: auto;
}
.center-transform /* needs width/height to be set */
{
position: absolute;
margin: auto;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
}
/* http://coding.smashingmagazine.com/2013/05/22/centering-elements-with-flexbox/ */
.center-flexbox
{
display: -webkit-box; /* OLD: Safari, iOS, Android browser, older WebKit browsers. */
display: -moz-box; /* OLD: Firefox (buggy) */
display: -ms-flexbox; /* MID: IE 10 */
display: -webkit-flex; /* NEW, Chrome 21–28, Safari 6.1+ */
display: flex; /* NEW: IE11, Chrome 29+, Opera 12.1+, Firefox 22+ */
align-items: center;
justify-content: center;
margin: 0;
height: 100%;
width: 100% /* needed for Firefox */
}
我有一個有效的示例: https : //jsfiddle.net/v1harbqm/7/
我以@gopalraju的小提琴為基礎。 它不是在Safari中工作,而是結合display: table;
並增加標題工作的高度。
編輯 :在標題內創建了一個<span>
,使其可以使用更長的文本。 這次使用轉換,看起來Safari仍需要-webkit-前綴,因此開始時可能是原始問題。
無論如何,這是更新的: https : //jsfiddle.net/v1harbqm/13/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.