Search code examples
htmlcssmarginmargins

Image is not centered even margin auto applied


Trying to move the picture to the centre of the page using CSS. I applied these values to the image, but no success. See code below:

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

Would really appreciate straight to the point answer and no downgrading please.


Solution

  • For margin: 0 auto to work you need to add 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" />


    EDIT:

    Actually...

    Don't change the default behavior of an element if you can avoid it. Keep elements in the natural document flow as much as you can.


    Since images behave like text by default, it is better if you do this:

    .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>