即使自动应用边距,图像也不居中

时间:2016-08-22 21:59:07

标签: html css margin margins

尝试使用CSS将图片移动到页面中心。我将这些值应用于图像,但没有成功。请参阅以下代码:

HTML:

<div class="list_of_reviews">
<ul style="list-style-type:none">
<li>What will happen to Brittish travelers when Brexit finaly happens</li>
</ul>
</div>
<img class="image_1" src="for left column.jpg" alt="What will happen to Brittish travelers when Brexit finaly happens"/>

CSS:

.list_of_reviews {
    margin:80px auto;
    font-family: "Times New Roman", Times, Serif;
    line-height: 1.5;
    font-size: 30px;
    width: 40%;     
    border:solid;
}


.image_1 {
    margin:auto;
    height:200px;
    width:350px;
    position:relative;
}

非常感谢直截了当的答案,请不要降级。

3 个答案:

答案 0 :(得分:2)

margin: 0 auto工作,您需要添加display: block

.list_of_reviews {
  margin: 80px auto;
  font-family: "Times New Roman", Times, Serif;
  line-height: 1.5;
  font-size: 30px;
  width: 40%;
  border: solid;
}
.image_1 {
  display: block;
  margin: auto;
  height: 200px;
  width: 350px;
  position: relative;
}
<div class="list_of_reviews">
  <ul style="list-style-type:none">
    <li>What will happen to Brittish travelers when Brexit finaly happens</li>
  </ul>
</div>
<img class="image_1" src="http://placehold.it/350x200" alt="What will happen to Brittish travelers when Brexit finaly happens" />

修改

实际上...

  

如果可以避免,请不要更改元素的默认行为。   尽可能多地保留自然文档中的元素。

由于默认情况下图像的行为与文本类似,因此最好执行此操作:

.list_of_reviews {
  margin: 80px auto;
  font-family: "Times New Roman", Times, Serif;
  line-height: 1.5;
  font-size: 30px;
  width: 40%;
  border: solid;
}
figure {
  text-align: center;
}
.image_1 {
  height: 200px;
  width: 350px;
  position: relative;
}
<div class="list_of_reviews">
  <ul style="list-style-type:none">
    <li>What will happen to Brittish travelers when Brexit finaly happens</li>
  </ul>
</div>
<figure>
  <img class="image_1" src="for left column.jpg" alt="What will happen to Brittish travelers when Brexit finaly happens" />
</figure>

答案 1 :(得分:2)

默认情况下,<img>设置为display: inline;(虽然它们在技术上具有某些display: inline-block;属性 - https://stackoverflow.com/a/2402773/3997209

您可以非常轻松地将其覆盖到display: block;,并且您所需的布局将有效:https://jsfiddle.net/er13qobj/

答案 2 :(得分:0)

相反,我会推荐这种方式,但它发现很傻,但仍然有效,

<div class="list_of_reviews">
<ul style="list-style-type:none">
<li>What will happen to Brittish travelers when Brexit finaly happens</li>
</ul>
</div>
<center>
<img src="for left column.jpg" alt="What will happen to Brittish travelers when Brexit finaly happens"/>
</center>