簡體   English   中英

CSS:在居中圖像周圍左右放置文本

[英]CSS: place text left and right around a centered image

我想在居中圖像的左側和右側放置文本。 看到:

<div style="position:relative; display: table; margin: 2em auto;">
    <span>TEXTSAMPLE 12345</span>
    <img src="http://placehold.it/350x150" style="height: 4em;">
    <span>12345</span>
 </div>

我想出了如何使整個內容居中,但我希望圖像不居中並相應地調整文本。

嘗試使用float,但我沒有得到適當的結果。 有任何想法嗎?

謝謝

您可以在父級上使用flex ,然后在text div上使用flex flex-grow (或簡稱為flex: 1 0 0 ),這樣它們將填充圖像剩余的所有可用空間(將圖像置於中心),然后在第一個跨度中使用text-align可以按圖像放置文本。 我也將您的img包裹在一個元素中,因為img是因為flex子項通常最終會拉伸。

 div { display: flex; } span:not(.img) { flex: 1 0 0; } span:first-child { text-align: right; } 
 <div> <span>TEXTSAMPLE 12345</span> <span class="img"><img src="http://placehold.it/350x150" style="height: 4em;"></span> <span>12345</span> </div> 

要獲得預期結果,請使用以下選項-display:flex將內容水平和垂直居中

CSS:

html,body{
  height:100%;

}
body, div{
  display:flex;
  align-items:center;
  justify-content:center;
}

HTML:

<body>
<div>
    <span>TEXTSAMPLE 12345</span>
    <img src="http://placehold.it/350x150" style="height: 4em;">
    <span>12345</span>
 </div>
</body>

Codepen- https: //codepen.io/nagasai/pen/vmeYzb

您可以創建一個無邊框的3列1行表格。 在第一個和最后一個單元格中,根據需要放置文本; 在中央放置圖片:

<table>
<tr>text 1</tr>
<tr><img...></tr>
<tr>text 2</tr>
</table>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM