문제

I have a very strange problem (or maybe I just worked to much on it to find the hint). I want to center an image with subtitle which is scalable. Here's my code:

HTML

<div class="parent">
    <div class="child">
        <img src="image.jpg" alt="">
        <br>
        <div>Title</div>
    </div>
</div>

CSS

.parent {
    width: 66%;

}

.child {
    width: auto;
    height: auto;
    margin: auto;
}

.child img {
    max-width: 100%;
    max-height: 95%;
    height: auto;
    width: auto;
}

.child div {
    display: inline;
    font-style: italic;
}

Now the interesting part. I want to get the image's current width and apply it to the .child; text-align: center won't work, that would cause my title to be in the center too.

But – if I'm reading out the image's width, I always get it's natural size, and not it's resized one. I'm really confused, I guess it's really obvious... here's my so far tried JS.

Javascript

$(window).load(function(){
    var $el = $('.child').find('img');
    $el.parent().css('width', $(this).width());

    // I also tried $(this).get(0).width, $(el).width() and $(el).css('width')
    // ...
});

Thanks for helping!

도움이 되었습니까?

해결책

please check this jsfiddle i created, it might be what you need:

http://jsfiddle.net/2kC3q/2/

I set the image to be resizable (to simulate for scalable).

The text is aligned in the center and when the image width and height are changed so is the child.

HTML:

<div class="parent">
    <div class="child">
        <img class="image" id="image" src="image.jpg" alt=""/>
            <br/>
        <div class="title">Title</div>
    </div>
</div>

CSS:

.parent {
    width: 66%;

}

.child {
    width: auto;
    height: auto;
    margin: auto;
    border: 1px solid black;
    display: inline-block;
}

.image{
    max-width: 100%;
    max-height: 100%;
    min-width: 50px;
    min-height: 50px;
    display: block;
    border: 1px solid red;
}

.title{
    text-align: center;
    display: block;
    font-style: italic;
}

Hope it helps.

다른 팁

try this:

$(window).load(function(){
$('.child').find('img').css({'width':parseInt($('.child').find('img').width())+'px', 'margin':'0 auto'});
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top