2013-01-01 148 views
-1

我如何對齊包含在水平一個div圖像?這是一個固定的寬度。對齊圖像水平

示例代碼:

HTML

<div id="random"> 
<a href=""><img src=".jpg" /><span></span></a> 
<a href=".html"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p> 
</div> 

CSS

#random{ 
max-width: 650px 
} 
+0

您這兒只有1個圖像和一些無效的HTML('了'不能包含塊級元素,比如'H2 '或'p')。您是否嘗試將圖像與「h2」對齊或以相同方式格式化爲另一幅圖像? – cimmanon

+0

在HTML5中,鏈接環繞塊級元素是完全有效的。 –

回答

1

通常可以漂浮做的伎倆來對齊元素水平相當不錯。在包含(父)元素上使用帶有clearfix類的聯合函數,以便浮動元素不會破壞其他頁面佈局。

HTML

<div class="horiz clearfix"> 
    <div><a href="www.google.com"><img src="https://www.pathe.nl/themes/main_theme/gfx/icons/placeholder-large.png"/> 
     </a></div> 
    <div><a href="www.stackoverflow.com"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p></div> 
</div> 
<div class="horiz clearfix"> 
    <div><a href="www.google.com"><img src="https://www.pathe.nl/themes/main_theme/gfx/icons/placeholder-large.png"/> 
     </a></div> 
    <div><a href="www.stackoverflow.com"><h2>Title</h2></a><p>Info</p><p>Dd/Mm/Yyyy</p></div> 
</div>​ 

CSS

/* 
* Clearfix: contain floats 
* 
* For modern browsers 
* 1. The space content is one way to avoid an Opera bug when the 
* `contenteditable` attribute is included anywhere else in the document. 
* Otherwise it causes space to appear at the top and bottom of elements 
* that receive the `clearfix` class. 
* 2. The use of `table` rather than `block` is only necessary if using 
* `:before` to contain the top-margins of child elements. 
*/ 

.clearfix:before, 
.clearfix:after { 
    content: " "; /* 1 */ 
    display: table; /* 2 */ 
} 

.clearfix:after { 
    clear: both; 
} 

/* 
* For IE 6/7 only 
* Include this rule to trigger hasLayout and contain floats. 
*/ 

.clearfix { 
    *zoom: 1; 
} 

.horiz > * { 
    float: left; 
    margin-right: 5px; 
}​ 
+0

注意,clearfix從[HTML5樣板(http://html5boilerplate.com/) – andersand

+0

和HTML5樣板複製尼古拉斯·加拉格爾複製(請參閱:http://nicolasgallagher.com/micro-clearfix-hack/)。 – cimmanon

-1

使用這樣的事情:

^h TML

<div id="random"> 
    <img src="1.jpg" /> 
    <img src="2.jpg" /> 
    <img src="3.jpg" /> 
</div> 

CSS

#random{ 
    max-width: 650px 
} 

#random img{ 
    display:inline-block; 
    width:80px; 
} 
0

.container{ 
 
    background:#d5d5d5; 
 
    } 
 
.container img{ 
 
    width:200px; 
 
    margin:0 auto; 
 
    display:block; 
 
    }
<div class="container"> 
 
    <img src="https://dummyimage.com/200X200/000/fff"/> 
 
</div>

+0

請解釋爲什麼這是一個解決方案,或者至少爲你發佈的內容添加一些解釋 – ItamarG3