5

div背景画像として左上隅にアイコンを含み、残りの部分にテキストを含むの特定のクラスがありますdiv。すべてのdivアイコンが表示されるように、最小の高さは 32 ピクセルです。

テキストが複数行あるdiv場合は最小高さよりも下に伸びて線がきれいに見えますが、1 行しかない場合はアイコンの中心に垂直に整列しません。

ここで JSFiddle

単一の行を垂直方向に揃える方法はありますが、複数の行がある場合は混乱しませんか?

.test {
    background-color: #98c5ff;
    color: #093d80;
    width: 400px;
    min-height: 32px;
    background-image: url("http://google.com/favicon.ico");
    background-repeat: no-repeat;
    padding-left: 42px;
}
<div class="test"><p>Short message</p></div>
<hr />
<div class="test"><p>Rather long message that should hopefully wrap on to a second line at some point.</p></div>
<hr />
<div class="test"><p>Message<br />with<br />many<br />lines<br />.</p></div>

4

7 に答える 7

8

display次のように CSS で使用できます。

.test {
    background-color: #999999;
    display: table; /* Add this in here. */
    width: 400px;
    min-height: 32px;
    background-image: url("http://google.com/favicon.ico");
    background-repeat: no-repeat;
    padding-left: 42px;
}

.test p {
    display: table-cell;
    vertical-align: middle;
}
于 2013-04-04T02:39:28.613 に答える
1

実際にはセンタリングではありませんが、視覚的にセンタリングし、一貫性を維持します。上部をパディングすることで解決できますが、その量は行の高さとフォント サイズによって異なります。

.test p:first-child{padding-top:8px}

一方、複数行の div の行の高さを変更してもかまわない場合は、「p」要素の行の高さを div の高さに合わせて設定できます。

.test {line-height:32px}

http://jsfiddle.net/eXZnH/34/

于 2016-03-05T12:40:27.110 に答える
1

さらに簡単なのは、CSS 内で ::before を使用することです

.test {
  position: relative;
  padding-left: 32px;
  background-color: #DDD;
}

.test::before {
  content: url(http://google.com/favicon.ico);
  position: absolute;
  left: 0;
  top: 50%;
  margin-top: -16px; /* image height divided by 2 */
}

それをチェックしてください

.test {
  position: relative;
  padding-left: 32px;
  background-color: #DDD;
}

.test::before {
  content: url(http://google.com/favicon.ico);
  position: absolute;
  left: 0;
  top: 50%;
  margin-top: -16px;
}
<div class="test">
<p>
bla bla bla<br />
bla bla bla<br />
bla bla bla<br />
bla bla bla<br />
bla bla bla<br />
</p>
</div>

<div class="test">
<p>bla bla bla bla</p>
</div>

于 2016-03-06T23:09:53.373 に答える
-1

まず、各 div の後にhrタグを使用しているため、それらを整列させることはできません。したがって、最初にそれらを削除してから、これらのスタイルを.testクラスに追加します

.test {
   // another styles..
   width: 130px; //small width for test
   display: inline-block;
   vertical-align: middle;
}
于 2016-03-07T15:01:23.610 に答える