2017-12-10 16 views
0

上のdivを中心I次のHTMLを持っている:.button-leftは常に画像の中心になるために私が達成したい何CSS - 垂直画像

<div class='container'> 
    <img src="http://lorempixel.com/400/400" /> 
    <div class='button-left'><</div> 
    </div> 

があり、どんなに画像サイズ、代わりにdivは私のhtml要素に従って配置されます。

これは私のCSSです:

.container img { 
    position: relative; 
} 
.button-left { 
    position: absolute; 
    top: 50%; 
    background-color: red; 
} 

は、相対位置する画像に応じて.button-left divの位置べきではないのですか?

あなたはライブデモを試してみたい場合にはJsBin: あなたがイメージにコンテナにposition: relativeを設定していないする必要がhttps://jsbin.com/cuwaguyiza/edit?html,css,output

+0

はい、垂直方向のみです。水平に私はそれがどこにとどまっていたいです:) –

+0

'.container {display:flex; align-items:center;} '&cssを削除します。 –

+0

.button-leftはあなたのケース.containerの親タグに絶対配置されるので、CSSルールを変更する必要があります –

答えて

1

。 また、ボタンを上に翻訳することをお勧めします。したがって、完全に中央に配置されています。

.container { 
    position: relative; 
} 

.button-left { 
    position: absolute; 
    top: 50%; 
    transform: translateY(-50%); 
} 
+0

なぜ 'transform:translateY(-50%);'を 'top:50%'と一緒に使用していますか? –

+0

要素の中心点は左上隅にあり、中心点にはありません。したがって、要素の高さの半分を 'position:top'から引く必要があります。 それ以外の場合、要素は中央に揃えられていませんが、要素の高さは下にオフセットされています – marcobiedermann

1

使用しない場合は、positionを使用しないでください。

  1. フレックスボックス。

    .container { 
     
        display: flex; 
     
        align-items: center; 
     
    }
    <div class='container'> 
     
        <img src="http://lorempixel.com/400/400"> 
     
        <div class='button-left'>Lorem</div> 
     
    </div>

  2. 行の高さ(Uテキストはシングルラインの場合)

.container img { 
 
    vertical-align: middle; 
 
} 
 

 
.button-left { 
 
    display: inline-block; 
 
    line-height: 400px; 
 
}
<div class='container'> 
 
    <img src="http://lorempixel.com/400/400"><!-- dont delete this comment 
 
--><div class='button-left'>Lorem</div> 
 
</div>

0
.container img { 
    position: relative; 
} 
.button-left { 
    left: 50%; 
    position: absolute; 
    top: 50%; 
    transform: translate(-50%, -50%); 
    background-color: red; 

} 

OR

.container img { 
    position: relative; 
    display: block; 
    margin: 0 auto; 
} 
関連する問題