How to put an image in div with CSS?

前端 未结 4 867
暗喜
暗喜 2020-11-28 20:05

I would like to have all my images in CSS (the only way I know how is to put them in as background images).

But the problem in this solution is you can never let the

相关标签:
4条回答
  • 2020-11-28 20:30

    With Javascript/Jquery:

    • load image with hidden img
    • when image has been loaded, get width and height
    • dynamically create a div and set width, height and background
    • remove the original img

        $(document).ready(function() {
          var image = $("<img>");
          var div = $("<div>")
          image.load(function() {
            div.css({
              "width": this.width,
              "height": this.height,
              "background-image": "url(" + this.src + ")"
            });
            $("#container").append(div);
          });
          image.attr("src", "test0.png");
        });
      
    0 讨论(0)
  • 2020-11-28 20:36

    This answer by Jaap :

    <div class="image"></div>​
    

    and in CSS :

    div.image {
       content:url(http://placehold.it/350x150);
    }​
    

    you can try it on this link : http://jsfiddle.net/XAh2d/

    this is a link about css content http://css-tricks.com/css-content/

    This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

    0 讨论(0)
  • 2020-11-28 20:36

    Take this as a sample code. Replace imageheight and image width with your image dimensions.

    <div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
    </div>
    
    0 讨论(0)
  • 2020-11-28 20:38

    you can do this:

    <div class="picture1">&nbsp;</div>
    

    and put this into your css file:

    div.picture1 {
       width:100px; /*width of your image*/
       height:100px; /*height of your image*/
       background-image:url('yourimage.file');
       margin:0; /* If you want no margin */
       padding:0; /*if your want to padding */
    }
    

    otherwise, just use them as plain

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