2013-01-01 111 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