如何水平对齐以下标题图像?

时间:2012-11-13 17:15:05

标签: html css image alignment

我整个下午都试过了,但是我错过了一些东西,有人可以帮我这个吗? 该页面可在以下链接中找到

The page with the image that I need fixed

包含图片的代码是:

    <headerimage><span>
            <img width="1920" height="600" src="http://www.websu.it/wp-content/uploads/2012/11/suitsheader.jpg" class="attachment-post-thumbnail wp-post-image" alt="Suits Header" title="Suits Header"></span>
        </headerimage>

我想在较小的屏幕上以1920px的宽度水平居中图像。当我给一个类属性background-position:top center时,它工作得很好,但是当我需要在页面中有一个-tag时,我似乎无法实现它。

请帮我看看:)这可能非常愚蠢,哈哈。 非常感谢!

3 个答案:

答案 0 :(得分:2)

在图片上设置margin: 0 auto;,例如:

<headerimage>
  <span>
    <img style="margin:0 auto;" width="1920" height="600" src="http://www.websu.it/wp-content/uploads/2012/11/suitsheader.jpg" class="attachment-post-thumbnail wp-post-image" alt="Suits Header" title="Suits Header">
  </span>
</headerimage>

答案 1 :(得分:1)

我不会把它作为图像而是作为标题的背景。

background-image:url('http://www.websu.it/wp-content/uploads/2012/11/suitsheader.jpg');
background-position-x:center;
background-repeat:no-repeat;

请参阅http://jsfiddle.net/dwat001/Q58YZ/进行粗略演示。

答案 2 :(得分:1)

如果你不能使用背景图像,另一种方法是使用javascript来定位图像。

<style>
  #imageHolder {
    overflow: hidden; // if image is bigger then holder, clip the image, no scollbars.
  }

  #wideHeaderImage {
    position: relative; // treat "left" as relative to the images normal position.
  }
</style>
<headerimage id="imageHolder">
  <img id="wideHeaderImage" width="1920".../>
</headerimage>

<script src="jquery"></script>
<script>
  // create function to center image;
  var centerImage = function($) {
     var windowWidth = $(window).width(); // get the current width of the window
     var imageSize = $('#wideHeaderImage').width(); // get width of image                                             
     $('#imageHolder').width(windowWidth); // set the containing element to be size of window.
     if(imageSize > windowWidth) { // if image is wider then window
       var offset = (imageSize - windowWidth) / 2; // Establish an offset
       $('#wideHeaderImage').css('left', '-' + offset + 'px'); // apply offset
     }
  };

  jquery(function($) {
    // this code runs within on load

    // register a resize event handler
    $(window).resize(function(event){centerImage($);});
    // resize once on onload.
    centerImage($);
  });
</script>

我没有这样做,所以我有可能犯了一些错误,希望你能够理解我正在做的事情。