LoginSignup
99
93

More than 5 years have passed since last update.

transformプロパティを使って要素を上下中央に配置する

Last updated at Posted at 2014-10-15

今回は上下中央に配置したいものの高さと幅が決まっていますが、この方法であれば文章などの不規則な高さのものも上下中央に配置可能です。

HTML

<div class="box>
    <img src="dummy.png alt="" width="24" height="24" class="img" >
</div>

CSS

.box {
   position:relative;
   height:300px;
}
.img {
   position: absolute;
   top: 50%;
   left: 50%;
   -webkit-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}

positiontop,leftで50%ずつ移動させ、要素の表示位置をtransformプロパティで調整するやり方です。
CSS3が使えず、今回のように要素の高さと幅が決まっている場合は、ネガティブマージンなどで調整しましょう。

99
93
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
99
93