2016-09-06 74 views
0

我試圖垂直和水平居中一次像這樣的專區內的股利banner_title水平位置的文字...CSS和圖像上方

.box { 
 
    text-align: center; 
 
} 
 
.banner_title { 
 
    font-size: 32px; 
 
    position: absolute; 
 
    top: 50%; 
 
    width: 100%; 
 
} 
 
.banner_title > div { 
 
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0; 
 
    color: #fff; 
 
    padding: 15px; 
 
}
<div class="box"> 
 
    <img src="http://dummyimage.com/1000x400/b895b8/fff.jpg&text=+"> 
 
    <div class="banner_title"> 
 
    <div> 
 
     THIS MESSAGE IS A TEST MESSAGE 
 
    </div> 
 
    <button> 
 
     This is a test button 
 
    </button> 
 
    </div> 
 
</div>

https://jsfiddle.net/j90gaawb/

這不適合我,任何人都可以幫忙嗎?

這就是我想實現...

enter image description here

+1

可能重複[如何垂直居中所有瀏覽器的div?](http://stackoverflow.com/questions/396145/how-to-vertically-center-a-div-for-all-瀏覽器) – henry

+0

這複製了許多現有的SO問題。檢查出http://stackoverflow.com/questions/396145/how-to-vertically-center-a-div-for-all-browsers和http://stackoverflow.com/questions/19461521/how-to-center- an-element-horizo​​ntal-and-vertical/19461564#19461564 – henry

回答

1

我會推薦以下方法

.box { 
 
    text-align: center; 
 
    display: table; 
 
    width: 100vw; 
 
    height: 100vh; 
 
} 
 
.banner { 
 
    font-size: 32px; 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
    height; 
 
    auto; 
 
    background-image: url('http://dummyimage.com/1000x400/b895b8/fff.jpg&text=+'); 
 
    background-size: cover; 
 
} 
 
.banner_title { 
 
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0; 
 
    color: #fff; 
 
    display: inline-block; 
 
} 
 
.banner_title > div { 
 
    padding: 15px; 
 
}
<div class="box"> 
 
    <div class="banner"> 
 
    <div class="banner_content"> 
 
     <div class="banner_title"> 
 
     THIS MESSAGE IS A TEST MESSAGE 
 
     </div> 
 
     <div> 
 
     <button> 
 
      This is a test button 
 
     </button> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

https://jsfiddle.net/j90gaawb/6/

1

這是你在找什麼?

.box { 
    text-align: center; 
    position: relative; 
    } 

.banner_title { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 

.banner_title > div { 
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;color: #fff; 
    padding: 15px; 
} 

小提琴:https://jsfiddle.net/j90gaawb/1/

+0

這很好,但如果我增加字體大小,它會繼續到2行,有沒有辦法改變這個斷點? https://jsfiddle.net/j90gaawb/2/ – fightstarr20

+0

不是這個答案的原始海報,但是這樣的事情呢? https://jsfiddle.net/r53o7wqb/。您明確設置寬度,但高度是動態的。 –

+0

@ fightstarr20,可以很容易地用白色空間固定:nowrap;見https://jsfiddle.net/j90gaawb/4/ –

1

試試下面的CSS:

.banner { 
    position: relative; 
} 

.box { 
    left: 0; 
    position: absolute; 
    text-align: center; 
    top: 30px; 
    width: 100%; 
}