How to set a max-width to a div that increases and decreases proportionally?

Asked

Viewed 1,676 times

12

My div which increases or decreases proportionally is with style:

padding-bottom: 75%;

Look at this example: Jsfiddle

What I want is that the div that grows proportionately lock the size, when you touch the footer. Otherwise, it grows infinitely.

Some solution?


Screens: primeira imagem First phase this ok.

segunda imagem In this second image, notice that he touched the footer, IE, it is for him to lock with this size staying as the third image.

terceira imagem

3 answers

3


See the result on Jsfiddle, using pure Javascript to manipulate the CSS properties of the slide element.

Note that the property padding-bottom: 75%; slide class was removed, since the dimensions of the slide are controlled by script.

Below, follow the script that performs the task:

var slide = document.querySelector('.slide'); 

var aspectRatio = 720/540;  // ou (4:3) proporção de aspecto do div .slide

function resize() {
    // dimensões da janela disponíveis
    var newHeight = document.documentElement.offsetHeight - 39; // 39 é o espaço ocupado pelo footer
    var newWidth = 0.8 * (document.documentElement.offsetWidth); // largura disponível: 80% do documento
    var newWidthToHeight = newWidth / newHeight;

    // ajusta o div mantendo as proporções de aspecto definidas por aspectRatio      
    if (newWidthToHeight > aspectRatio) {
      newWidth = newHeight * aspectRatio;
    } else {
      newHeight = newWidth / aspectRatio;
    } 
    slide.style.width = newWidth + 'px';
    slide.style.height = newHeight + 'px';
}

// efetua um redimensionamento inicial
resize();

// redimensiona o slide sempre que a janela for redimensionada
window.addEventListener('resize', resize, false);

// (!) utilize a função resize sempre que o div .slide sofrer alterações

Whenever an element needs to be resized according to an aspect ratio("Aspect ratio"- in English), a similar strategy may be used.

I do not know if it is possible to achieve the same results through CSS Media Queries or another strategy that uses purely CSS, but if possible always prefer the use of CSS.

  • Note: The above script is not 100% cross-browser, since querySelector and document.documentElement.offsetWidth may not be available in older browsers, but it is quite simple to adjust it as needed, for example using jQuery if you already use it in the document in question. =)

  • perfect @Gustavocarvalho, just a little problem. The body is with a margin, how do I remove it? I put a margin:0 on it, only then the slide gets a space between the right side.

  • Another thing, I’ll have two slide classes and it only works on the first.

  • @Jeffersonalison, To remove body margin just add in body CSS margin: 0 0 0 0; But then you have to adjust the script in newWidth(the discount of 16 was given on account of the margin, check the updated reply). For more than one slide just divide the available height by the number of slides. Check in this fiddle.

1

The best way to do so is to use CSS media queries, not javascript. Please avoid suggesting doing javascript something that can be done in pure CSS. Javascript adds additional complexity and should be avoided if simpler means exist.

It’s simpler and works everywhere, and even when it doesn’t work and the developer makes sure it works on older browsers like IE8, it would also need javascript to force the operation.

In https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries has a good guide on Media Queries.

A very short example of this:

/* entre 1024px e 1200px uma barra lateral seria ocultada */
@media (min-width: 1024px) and (max-width: 1200px){
    .sidebar-b {
      display: none;
  }
}
  • I fully agree that you should use CSS when you can use it. But in this case I don’t see how not to use JS. You can try giving an example with CSS using jsFiddle of Jefferson?

  • 1

    If @Jefferson Alison informs the break points and selector of the elements to be broken, yes.

  • @Emersonrochaluiz, you say the breaking points type: "ah la at 1024px width this breaking, la at 1200px is breaking" ?

  • Ex: w > 0 && w <= 768px: Image 1; w > 768px && w < 1200px: Image 2; and so on where w is screen width at px or em (if use em)

1

To do this you will have to use a few things and a little math.

You can take the size of the elements in 3 ways:

  1. $(ele).height - Does not count padding, border and margin measures;
  2. $(ele).innerHeight - Does not count border and margin measures, but accounts for padding;
  3. $(ele).outerHeight - Does not account for margin measures by default, but accepts a parameter that allows accounting;

Knowing this, you can get window (viewport) or Document (full page) size. The difference between the two is that window is the size of the visible area in the browser and Document is the whole page, even the elements hidden by the position.

With this information, you just need to define a rule (and a time to execute this rule) where your code evaluates the size of the viewport or Document and establishes the max-height of the element that cannot grow too much.

You can run the function for example every time something is written on that element, or just on DOMReady page.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.