【问题标题】:align images horizontally水平对齐图像
【发布时间】:2016-12-20 21:06:50
【问题描述】:

如何水平对齐 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
}

【问题讨论】:

  • 这里只有 1 张图片和一些无效的 HTML(a 不能包含块级元素,如 h2p)。您是否尝试将图像与h2 或以相同方式格式化的另一张图像对齐?
  • 在 HTML5 中,链接环绕块级元素是完全有效的。

标签: html css alignment


【解决方案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;
}​

【讨论】:

【解决方案2】:

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

【讨论】:

  • 请解释为什么这是一个解决方案,或者至少对您发布的内容添加一些解释
【解决方案3】:

使用这样的东西:

HTML

<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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 2012-08-23
    相关资源
    最近更新 更多