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
655 views
in Technique[技术] by (71.8m points)

image - Proportionally scale a div with CSS based on max-width (similar to img scaling)

Is it possible to proportionally scale a div like an img using only CSS? Here is my first attempt: http://dabblet.com/gist/1783363

Example

div {
 max-width:100px;
 max-height:50px;
}
img {
 max-width:100px;
 max-height:50px;
}

Actual Result

Container: 200 x 100
Div:       100 x 50
Image:     100 x 50

Container: 50  x 100
Div:       50  x 50  // I want this to be 50x25, like the image
Image:     50  x 25
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Since vertical paddings set in percent are calculated out of width of an element we can make a div always be of a certain aspect ratio.

If we set padding-top:50%; height:0, the height of the div will always be half of its width. And to make text appear inside such a container you need to make it position:relative and put another div inside it and position it absolutely 10px away from all four sides (the padding you set first).

See my fork of your code.


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

...