JSFiddle - React, Tailwind, and code Playground
by oti ext
HTML
<h1>インライン要素を絶対中央配置する</h1>
<p>スニペットは以下。</p>
<pre title="HTML"><code data-language="html"><div class="wrap">
<img class="target" src="https://placekitten.com/g/250/250">
</div></code></pre>
<pre title="CSS"><code data-language="css">.wrap {
position: relative;
}
.target {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}</code></pre>
<h2 id="sam1">1)インラインブロック要素を絶対中央配置</h2>
<div class="wrap">
<img class="target" src="https://placekitten.com/g/250/250">
</div>
<p>img要素にwidth属性やheight属性がなくても中央に配置してくれる。素敵なのでこれを画像じゃない要素でやりたい。(※Opera 11.62 では width 属性と height 属性を指定しないと中央配置にならなかった)</p>
<p><ins datetime="2013-03-04T13:40+09:00">2013/3/4 追記)Opera 12.12 で width/height 属性によるサイズ指定がなくても絶対中央配置になっていることを確認した。</ins></p>
<h2 id="sam2">2)ブロック要素を絶対中央配置</h2>
<pre title="CSS"><code data-language="css"><mark>div</mark>.target {
background: #a6a9af;
}</code></pre>
<div class="wrap">
<div class="target">ブロック要素</div>
</div>
<p>ブロックだから親に対してビタビタ。サイズが同じなだけで中央には配置されてるとは言える。</p>
<h2 id="sam3">3)要素にサイズを与える</h2>
<pre title="CSS"><code data-language="css">div.target.sizing {
<mark>width: 200px;</mark>
<mark>height: 200px;</mark>
background: #a6a9af;
}</code></pre>
<div class="wrap">
<div class="target sizing">サイズを与えたブロック要素</div>
</div>
<p>サイズを与えれば絶対中央配置される。</p>
<h2 id="sam4">4)インライン要素を絶対中央配置</h2>
<pre title="CSS"><code data-language="css"><mark>span</mark>.target {
background: #a9afa6;
}</code></pre>
<div class="wrap">
<span class="target">インライン要素</span>
</div>
<p>インライン要素にスニペットをあてるとブロック化されてないのに親要素にビタビタする。これがtop,bottom,left,rightプロパティ全指定の力...</p>
<h2 id="sam5">5)インライン要素にサイズを与える</h2>
<pre title="CSS"><code data-language="css">span.target.sizing {
<mark>width: 200px;</mark>
<mark>height: 200px;</mark>
background: #a9afa6;
}</code></pre>
<div class="wrap">
<span class="target sizing">サイズを与えたインライン要素</span>
</div>
<p>ブロック化してないのにサイジングできた。これがtop,bottom,left,rightプロパティ全指定の力!</p>
<h2...
CSS
html{margin:0;padding:0;}
body {
margin: 0;
padding: 10px;
color: #363636;
font-size: 90%;
line-height: 1.6;
background: #efefef;
}
ins {
color: #bf1212;
text-decoration: none;
}
img {
margin: 0;
padding: 0;
}
.wrap {
width: 100%;
height: 300px;
position: relative;
background: #333333;
overflow:hidden;
resize:both;
}
.wrap2 {
width: 100%;
height: 300px;
position: relative;
background: #336699;
resize:both;
}
.target {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
div.target {
background: #a6a9af;
}
span.target {
background: #a9afa6;
}
.sizing {
width: 200px;
height: 200px;
}
.target2 {
position: absolute;
top: 50%;
bottom: 50%;
left: 50%;
right: 50%;
margin: -25%;
background: #afa6a9;
}