Sizing width of an element as a percentage of its

2019-03-27 17:06发布

问题:

This question already has an answer here:

  • Maintain the aspect ratio of a div with CSS 21 answers

Im making a responsive design, which has to keep the proportions of its elements (height to width) no matter what the screen size is, so i don't know the size in pixels for any of the elements and i can work only in %.

I can set either the width or the height as a % of the browser size, but the i have no idea how to set the other property value.

That using only CSS, making JS calculate the values is not an option.

回答1:

I came across this problem last year and found an obscure solution after some tedious researching. Unfortunately it involves wrapper DIVs. The structure is simple - you have a parent DIV which contains the contents container and another DIV that sets the proportions. You set the margin-top of the 'proportion' DIV as percent of the width of the parent... Example:

#parent {
    position: relative;
}
.proportions {
    margin-top: 75%; /* makes parent height to 75% of it's width (4:3)  */
}
.container { /* contents container with 100% width and height of #parent */
    position: absolute;
    top: 0px;
    left: 0px;
    bottom: 0px;
    right: 0px;
}

http://jsfiddle.net/twpTU/



回答2:

Use CSS calc() https://developer.mozilla.org/en-US/docs/Web/CSS/calc It has pretty good adoption for modern browsers http://caniuse.com/calc as a fall back use CSS media queries and have min widths and heights to fall back on.

Obviously you could always just calculate both percentages in advance.

Div1 needs a height of 60% and the width needs to be 1/4th the height. 60% * .25 = width: 15%

div {
    position: absolute;
    border: 2px solid black
}
#div1 {
    width: 40%;
    height: calc(40% * 1.2);
}
#div2 {
    width: calc(90% / 4);
    height: 90%;
}

http://jsfiddle.net/pU4QA/



回答3:

First, I know that the OP has clearly mentioned that he is not looking for any Javascript approach, however I think it might be useful for couple of people who are still open to use Javascript as well.

Here is the answer; To set the size for both width and height in the same percentage, you can set the width of the parent element to width: 100%; via CSS, then with Javascript you set the height of the parent to the size of width. Then you would have a square-shaped element as the parent.

Now you can apply both width: 10%; height: 10%; to the child elements. Then only things you need to do in order to keep it responsive is to listen for the window resize event and then you apply the height again only to the parent, and all children will be updated.

http://jsfiddle.net/sDzHb/

Something like this will keep it responsive to the browser size:

$(window)
    .resize(function() {
        var w = $(document).width();
        $('.parent').height(w);
    })
    .trigger( 'resize' );


标签: css layout fluid