开发者

Fluid Images: How to set width and height?

I'm trying to build a fluid layout, for which I am styling big images with:

.fl开发者_开发问答uid_img {
  height: auto;
  width: auto;
  max-width: 100%;
}

This works fine, the problem is that I can no longer use the width and height attributes in the html img tag (they will have no effect). I need those attributes so the browser can "save" the space needed for the image before it has been loaded, so the rest of the page don't move when the image is loaded.

Is there any way to have both features? (fluid image + space saved before image load)


I'm also looking for the answer to this problem. With max-width, width= and height=, the browser has enough data that it should be able to leave the right amount of space for an image but it just doesn't seem to work that way.

I worked around this with a jQuery solution for now. It requires you to provide the width= and height= for your <img> tags.

CSS:

img { max-width: 100%; height: auto; }

HTML:

<img src="image.png" width="400" height="300" />

jQuery:

$('img').each(function() { 
    var aspect_ratio = $(this).attr('height') / $(this).attr('width') * 100;
    $(this).wrap('<div style="padding-bottom: ' + aspect_ratio + '%">');
});

This automatically applies the technique seen on: http://andmag.se/2012/10/responsive-images-how-to-prevent-reflow/


Inline styles overrule stylesheet styles by design. The cascade in CSS goes external stylesheet(s) (read top to bottom, so bottom would overrule top), styles in <head> (also top to bottom), inline styles, user styles. There are a number of ways to handle this, bu I don't know if any of them are really a good idea, as asked.

1) set your fixed dimension in the style sheet or head or inline, then overrule it with a script placed further down the page for auto dimensions. <script>vdivid.style.width = 'auto'</script>

2) make an <img> with fixed dimensions wrapped in a <div> with auto dimensions. this doesn't actually do what you want though. `

3) web optimize your images so that they don't take a long time to load.

4) dimensions set in pixels are generally not something you use in fluid layouts, since they are fixed. so do #fluiddiv {width:20%;height:20%;} that's how fluid layout works. or you can use em's instead of %'s. em's flex based on the default font size for the device, while %'s flex based on the dimensions of the window or parent element (if it has a parent other than body or a top-level wrapper). To get non-distorted images this way would require... I don't think you can do it with %'s, so use em's in the same ratio as the images.


This can be easily done with modern CSS3, and HTML5 semantic elements.

with tags like "nav, main, figure, article, and section" you can get a coherent structure for your site, then apply some style to the document using CSS GRID and CSS variables. You will get the job done with no effort, and you dont even need Javascript.

look at this example:

@charset "UTF-8";
:root{
  --w:#fff;
  --x:100%/600;
  --bu:#e15f41;  
  --m:#786fa6;
  --v:400;
  --n:#f8a5c2;
  --z:400/600;
  --t:#333;
  --r: calc(var(--z)*100%);
  --b:#000;
}

body{
  margin: 1rem;
	padding: 0;
	border: 0;
  outline: 0;
	font-size: 100%;
	font: inherit;
  color: var(--t);
	vertical-align: baseline;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: var(--b);
  min-width: 100px;
  display: grid;
}
nav{
  text-align: center;
  background-color: var(--n);
  padding: .3rem;
}
h1, h2, h3{
  color: var(--w);
}
ul{
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  list-style: none;
  padding: .2rem;
}
a{text-decoration: none; color: var(--b);}
a:hover{color:var(--w);text-shadow: 1px 1px 3px var(--t);}
main{
  display: grid;
  min-width: 100px;
  background-color: var(--m);
  padding: 1em;
}

figure{
  --i:calc(var(--x)*var(--v));
  margin: 0;
  position: relative;
  
  border: 4px solid white;
  padding-top: var(--i);
}
img{
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background-color: #888;
}

button{
  background-color: var(--bu);
  position: fixed;
  width: 50px;
  height: 50px;
  font-size: 1.2rem;
  bottom: 15px;
  right: 15px;
  z-index: 100;
  padding: 10px;
  border-radius: 50%;
  outline: 0;
  box-shadow: 0px 0px 6px 3px rgba(0, 0, 0, 0.5);
}
button:hover{
  --buh:#e77f67;
  cursor: pointer;
  background-color: var(--buh);
}

@media only screen and (min-width: 600px){
  main{
    padding: 1.5em;
    min-width: 100px;
    background-color: var(--m);
    display: grid;
    grid-template-columns: repeat(2,1fr);
    grid-gap: .5em;
  }
}

@media only screen and (min-width: 1080px){
  main{
    padding: 2em;
    min-width: 100px;
    background-color: var(--m);
    display: grid;
    grid-template-columns: repeat(3,1fr);
    grid-gap: .8em;
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="master.css">
<title>Document</title>
</head>
<body>
  <header>
        <nav>
          <h1>site title</h1>
          <ul class=''>
            <li><a href="#">menu1</a></li>
            <li><a href="#">menu2</a></li>
            <li><a href="#">menu3</a></li>
            <li><a href="#">menu4</a></li>
            <li><a href="#">menu5</a></li>
          </ul>
        </nav>
  </header>
    <main>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
      <section>
        <h3>Random Title</h3>
        <figure>
          <img class="on-off" src="" alt="image not found">
        </figure>
        <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></article>
      </section>
    </main>
  <footer>
        <button type="button" onclick="onOff();">&#x21c4;</button>
  </footer>
  <!--The following javascript is for demonstration purposes only and is not necessary-->
  <script>
  function onOff() {
    let images = document.querySelectorAll('.on-off');
    for (let i = 0; i < images.length; i++) {
        if (images[i].getAttribute('src')=="") {
        images[i].setAttribute('src', "https://upload.wikimedia.org/wikipedia/commons/6/6b/Delizia_del_Verginese%2C_tra_arte_e_natura.jpg")
        }
            else {
            images[i].setAttribute('src', "")
            }
    }
  };
  </script>
</body>
</html>

Important NOTE:

the javascript it is there for demostation purposes only, to toggle images on and off and has no interaction with the layout. take a look at this PEN

You should optimize the images to a proper size and weight, especially if they are big.


You can use a parent div with a percentage padding based on aspect ratio as described here.

The solution is ugly and I'm surprised that although fluid images are really old there's not much talk about this problem or an elegant solution.


Use the following:

 <img class="fluid_img" src="..." style="width: 50px; height: 100px;">

The inline-styles will override whatever styles are being attached from the fluid_img class based on precedence. You can see this by going to CSS in Firebug / Chrome and viewing which styles are being applied to your img.

Additionally, you can use the following jQuery if it would help when you are dynamically inserting / changing images:

 $('<img>').src('...').css({width: 50, height: 100});

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜