Вопрос

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