2016-07-17 10 views
3

div内にテキストを縦横に配置したい。 divには兄弟画像も含まれています。div内に兄弟画像を含むテキストを中央に配置

.div-table { 
 
    display: table; 
 
    vertical-align: middle; 
 
    z-index: 2 
 
} 
 
.div-table-cell { 
 
    display: table-cell; 
 
} 
 
.container { 
 
    width: 100%; 
 
    height: 100%; 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    color: red; 
 
}
<div> 
 
    <img src="https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" height="250" width="250" /> 
 
    <div class='container'> 
 
    <div class='div-table'> 
 
     <div class='div-table-cell'> 
 
     <p>my text</p> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>

私はで私がどこでjsfiddleを準備している:私は持っ思っhttps://jsfiddle.net/p3wur6qj/1/

display: table-cell; 

display: table; 

を含むdivの周りはこれを達成しますが、そうではありません。

+0

あなたがするトリングているもの[この](https://css-tricks.com/centering-percentage-widthheight-elements/)ですか? 'transform:translate(-50%、-50%);' 'magic"? –

+0

これが動作するかどうかを確認してください:https://jsfiddle.net/wy0qonb9/ –

答えて

2

フレックスボックスを使用して、テキストを水平方向と垂直方向の両方にセンタリングすることをお勧めします。 position + transformトリックを使用して

.container { 
 
    display: inline-block; /*same size as the image*/ 
 
    position: relative; 
 
} 
 
.content { 
 
    position: absolute; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100%; 
 
    height: 100%; 
 
    color: red; 
 
    display: flex; 
 
    justify-content: center; /*center horizontally*/ 
 
    align-items: center; /*center vertically*/ 
 
}
<div class='container'> 
 
    <img src="https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" height="200" width="200" /> 
 
    <div class='content'> 
 
    <p>my text</p> 
 
    </div> 
 
</div>

または、。

.container { 
 
    display: inline-block; 
 
    position: relative; 
 
} 
 
.content { 
 
    position: absolute; 
 
    left: 50%; 
 
    top: 50%; 
 
    transform: translate(-50%, -50%); /*position -50% of the element size*/ 
 
    color: red; 
 
}
<div class='container'> 
 
    <img src="https://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg" height="200" width="200" /> 
 
    <div class='content'> 
 
    <p>my text</p> 
 
    </div> 
 
</div>

関連する問題