Center an Image vertically and horizontally using CSS

前端 未结 10 1048
遥遥无期
遥遥无期 2020-11-30 08:12

How do I vertically and horizontally center an image when I do not know the size of it? I asked this question and someone suggested using a table. This isn\'t the first time

相关标签:
10条回答
  • 2020-11-30 08:33

    If you don't mind losing the img-tag, you can use background-image to center an image in a container block.

    markup:

    <div class="imagebox" style="background-image: url(theimage.png);"></div>
    

    style:

    .imagebox
    {
      width: 500px;
      height: 500px;
      border: solid 1px black;
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }
    
    0 讨论(0)
  • 2020-11-30 08:34

    Using CSS there is no easy way to vertically align an image center. Though to align it center horizontally you can use the following

    <img src="randomimage.jpg" style="margin: 0px auto;" />
    

    I would not reccommend a table for laying out an image as it is not really good practice anymore. Tables should only be used for tabular data.

    0 讨论(0)
  • 2020-11-30 08:36

    I end up doing the below. Tested with firefox, chrome, IE8 and opera. All good.

    table.NAME
    {
        background: green; //test color
        text-align: center;
        vertical-align:middle;
    }
    table.NAME tr td
    {
        width: 150px;
        height: 150px;
    }
    

    html

    <table class="NAME"><tr>
    <td><a href="jdhfdjsfl"><img src="dfgdfgfdgf.gif" alt="dfgdfgfdgf.gif"/></a></td>
    <td><a href="jdhfdjsfl"><img src="dfgdfgfdgf.gif" alt="dfgdfgfdgf.gif"/></a></td>
    ...
    
    0 讨论(0)
  • 2020-11-30 08:46

    Basically, you should be able to create a table in HTML, and the styling for the td tag should set the text-align attribute to center and the vertical-align attribute to middle. And, you can mess with other attributes, like borders, padding, etc...

    0 讨论(0)
提交回复
热议问题