2

さて、これが私の問題です。幅 348 ピクセルのブロックがあり、右側の 144 ピクセルで、画像を垂直方向に中央揃えにしたいと考えています。簡単ですよね?私の問題は、画像またはブロックの高さがわからないことです。背景画像にせずにコンテナの上部を通過するように画像を垂直方向に中央揃えするにはどうすればよいですか?

CSS
#block { width: 348px; position: relative; }
#content { width: 164px; padding: 20px; margin-right: 144px; }
#image { width: 144px; position: absolute; right: 0; }

MARKUP
<div id="block">
    <div id="image"><img url="imageurl" /></div>
    <div id="content">Some content goes here.</div>
</div>

どれだけ効果があるかわかりませんが、何かの役に立てば幸いです。

4

2 に答える 2

2

現在の HTML マークアップに基づいて、タグで指摘されているように、CSS のみを使用するソリューションは、次のように実現できます。

この実用的なフィドルの例を見てください!

ここに画像の説明を入力

HTML

<div id="block">
    <div id="content">Some content goes here.</div>
    <div id="image">
        <img src="path_to_image" />
    </div>
</div>

CSS

#block {
    width: 348px;
    display: table;         /* set the main wrapper to display as a table */
}
#content {
    width: 164px;
    padding: 20px;
}
#image {
    width: 144px;
    display: table-cell;    /* set the inner wrapper to display as a cell */
    vertical-align: middle; /* tell to vertically align the contents */
}

position使用されている技術と競合するいくつかの css 宣言を削除する必要がありました。ただし、それらがなくてもまったく同じレイアウトを実現できるため、CSSvertical-align:middleは期待どおりに機能します。


既存の CSS 宣言を削除せずに、まったく同じ目標を達成する、マークアップに対する jQuery ソリューション:

この実用的なフィドルの例を見てください!

ここに画像の説明を入力

jQuery

img内側に移動#imageして高さを収集し、それを 2 で割り、結果の値で負のマージンを適用します。

$(function() {
  var $target = $('#image').find('img');

  $target.css({
    "margin-top" : "-" + ($target.height()/2) + "px" // adjust the top margin
  });
});

CSS

#block {
    width: 348px;
    position: relative;
}
#content {
    width: 164px;
    padding: 20px;
    margin-right: 144px;
}
#image {
    width: 144px;
    position: absolute;
    right: 0;
    top: 0;              /* fit to the top */
    bottom: 0;           /* fit to the bottom */
    /*overflow:hidden;*/ /* optional if the img is bigger that this container */
}
#image img {
    position: absolute;  /* remove element from the document flow */
    top: 50%;            /* move it down by 50% of its parent height */
}

HTML

<div id="block">
    <div id="image">
        <img src="path_to_image" />
    </div>
    <div id="content">Some content goes here.</div>
</div>

現在のマークアップは保持され、それを機能させるために追加の css が追加されました。jQueryの部分はできるだけシンプルに!

于 2012-06-26T22:17:39.093 に答える
1

コンテナ内に画像を絶対に配置できますが、それがうまくいかない場合は、javascript を使用してコンテナの高さと画像の高さを取得し、そのように画像を配置する必要があります。

CSS 経由で設定するには:

コンテナ要素に「position:relative」のスタイルを設定します。次に、画像のスタイルを「position:absolute; top:50%;」に設定します。コンテナに高さを追加する必要がある場合もあります。

于 2012-06-26T20:21:13.120 に答える