Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

html - Bootstrap different img size at lg, md sm and xs

I need to make a image change it's size if the viewer has a smartphone or a PC. This achieves what I want but it's a bad way to do it because of loading the img 4 times and it's redundant:

<div class="col-md-4 text-center">
    <img class="hidden-md hidden-sm hidden-xs" src="~/Content/Images/masinaC.png" width="250" height="250" />
    <img class="hidden-lg hidden-sm hidden-xs" src="~/Content/Images/masinaC.png" width="200" height="200" />
    <img class="hidden-lg hidden-md hidden-xs" src="~/Content/Images/masinaC.png" width="150" height="150" />
    <img class="hidden-lg hidden-md hidden-sm" src="~/Content/Images/masinaC.png" width="100" height="100" />
</div>

It displays only one image at once, and only the size differs. How to achieve it without this ugly markup? Possibly with CSS, I put the image sizes in HTML just for simplicity.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are multiple solutions to this, depending on the results you are looking for. Try the JSFiddle's behaviour by resizing the result's cell.

1. Using width percentage

You can set a percentage width to the image so it adapts depending on the size of the screen. This solution may increase the size of the image if the percentage is bigger than the original width, e.g., if the image is 250px wide, and you use width: 50%, and the screen width is 600px, the image will be scaled until it is 300px wide.

See JSFiddle.

1.1 Using width percentage, with fixed width parent

If you want to use the previous solution but don't want the image to scale larger than the original size, you can set a parent with max-width.

See JSFiddle.

2. Using breakpoints

Using CSS3 media queries to change the size of the image depending on the screen's width range.

See JSFiddle.

You can read more about media queries and responsive CSS here.

If you don't want to use custom media query sizes and you want to stick with the Bootstrap-specific breakpoints, your CSS should be:

/* xs */
img {
    width: 100px;
    height: auto;
}
/* sm */
@media (min-width: 768px) {
    img {
        width: 150px;
    }
}
/* md */
@media (min-width: 992px) {
    img {
        width: 200px;
    }
}
/* lg */
@media (min-width: 1200px) {
    img {
        width: 250px;
    }
}

See JSFiddle. These sizes are documented here. xs is the default because Bootstrap 3 uses a mobile-first approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...