Mickey
Mickey

Reputation: 1505

Changing HTML with media queries?

I'm building my first website, using right now mainly HTML and CSS. In order to adjust my website for big screens (desktop computers) as well for tablets and phones, I'm using media queries to link my HTML pages to different style sheets. for example:

<head>
    <link rel="stylesheet" type="text/css" href="desktop_css.css" media="(min-width: 1200px)">
    <link rel="stylesheet" type="text/css" href="phone_css.css" media="(max-width: 1200px)">
</head>

That works really fine, but I need to change my HTML code as well. I want to add different images for every "media query", so that for under 1200px width of screen one image will appear, and another for screens with over 1200px width.

How do I do that?

Thanks alot!

Upvotes: 2

Views: 2306

Answers (2)

smoggers
smoggers

Reputation: 3192

What you could do is have all images within the HTML content and then in each CSS file you could just use display: none; to switch image visibility depending on screen-width.

jsfiddle

@media screen and (max-width: 1200px) {
   #img1 {
      display: none;
   }
}
@media screen and (min-width: 1200px) {
   #img2 {
      display: none;
   }
}
<div>
  <img id="img1" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcS0Dav0HDgMJbLCtT-V5EtyNf76ZO5O8SSx_f3Xs-hM_hNvYL6vwnvJ9g" />
  <img id="img2" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTmp65xRN2P3FI_nzAj06DyQ_qIsYF3SIvZfdIRFkTlR7EF734x" />
</div>

So in your case with external CSS files you would put the MediaQuery containing #img1 {display: none;} within phone_css.css and then the MediaQuery containing #img2 {display: none;} in desktop_css.css

Upvotes: 2

Ted Whitehead
Ted Whitehead

Reputation: 1826

I would recommend reading this great series of posts on responsive images: http://blog.cloudfour.com/responsive-images-101-definitions/

It does a great job describing the two main methods for doing this: srcset and <picture>.

If you care about cross-browser support, I would recommend using Picturefill: https://scottjehl.github.io/picturefill/

Upvotes: 0

Related Questions