Using Media Queries for Image Styling

Designing a website that caters to both desktop and mobile users has been my recent project. Utilizing media queries for responsiveness has been effective overall. However, there's one specific scenario where I'm facing some challenges.

On desktop view, I have a set of images with text overlay arranged in a particular layout:

https://i.sstatic.net/rsEfX.png

When transitioning to mobile view, I envision displaying these images in two columns, with the last tile spanning across the full width as shown below:

https://i.sstatic.net/D7HCf.png

The issue arises when the image used for the final tile on desktop is square, resulting in it appearing disproportionately large when spread across the full width on mobile devices, like so:

https://i.sstatic.net/lpd2C.png

Here's the current HTML and CSS code snippet I'm working with:

<div>
    <div class="hotel_container">
        <div class="options">
            <div class="option">
                <a href="www.example.com" target="_blank"><img class="opt_img" src="images/example.jpg"></a>
                <h3 class="centered" id="hotel_info">TEXT</h3>
            </div>
        </div>
        <!-- repeated "options" div 7 more times -->
        <div class="options_last">
            <div class="option">
                <a href="www.example.com" target="_blank"><img class="opt_img" src="images/example2.jpg"></a>
                <h3 class="centered" id="hotel_info">TEXT</h3>
            </div>
        </div>
    </div>  
</div>

CSS

.options, .options_last{
    width: 33%;
    overflow: hidden;
    display: inline-block;
}

@media only screen and (max-width: 812px) {
    .options{
        width: 50%;
    }
}

@media only screen and (max-width: 812px) {
    .options_last{
        width: 100%;
    }
}

.option{
    position: relative;
    text-align: center;
    padding: 10px;
}

@media only screen and (max-width: 812px) {
    .option{
        padding: 1px;
    }
}

.opt_img{
    width: 100%;
    opacity: 0.7;
}

.opt_img:hover{
    opacity: 0.9;
}

.centered {
    position: absolute;
    width: 100%;
    top: 40%;
    left: 50%;
    transform: translate(-50%, -50%);
}

#hotel_info{
    background-color: rgba(130, 130, 130,0.7);
    width: 80%;
    font-size: 23px;
    padding: 15px;
}

@media only screen and (max-width: 812px) {
    #hotel_info{
        width: 60%;
        font-size: 10px;
        padding: 5px;
    }
}

I'm hesitant about forcing a specific height for the image to avoid distortion. One solution could be using a rectangular image to switch dynamically on mobile views. However, implementing this based on device type without resorting to traditional media queries seems puzzling to me.

[Edit: Although hiding/showing alternate images with media queries is an option, it can impact page loading times due to all images being preloaded regardless of device type. Seeking advice on a more efficient approach rather than forming habits detrimental to performance]

If someone could guide me or recommend a simplified online resource to assist in tackling this issue, that would be greatly appreciated.


P.S. I'm fairly new to web development, so easy-to-understand answers are preferred. Your patience in clarifying any questions I may have is also valued. Additionally, open to suggestions for improved or streamlined methods based on my foundational learning from Codecademy web development courses.

Answer №1

If you're looking to experiment with CSS, one option is to explore the clip property.

.clippable {
    position: absolute; 
    clip: rect(0px,250px,100px,0px);
}

.flex-flow {
  align-self: auto;
  
}

.flow-box {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 250px;
  justify-content: space-between;
}
<div class="flow-box">
  <img src="https://pbs.twimg.com/profile_images/883859744498176000/pjEHfbdn_400x400.jpg" width="100" height="100" class="flex-flow"/>
  <img src="https://pbs.twimg.com/profile_images/883859744498176000/pjEHfbdn_400x400.jpg" width="100" height="100" class="flex-flow"/>
  <img src="https://pbs.twimg.com/profile_images/883859744498176000/pjEHfbdn_400x400.jpg" width="100" height="100" class="flex-flow"/>
  <img src="https://pbs.twimg.com/profile_images/883859744498176000/pjEHfbdn_400x400.jpg" width="100" height="100" class="flex-flow"/>
</div>

  <img src="https://pbs.twimg.com/profile_images/883859744498176000/pjEHfbdn_400x400.jpg" width="250" height="250" class="clippable"/>

Answer №2

If you want to hide or show elements based on different screen sizes, you can use media queries. For example, the most common breakpoints are 0 to 768px for mobile devices, 768px to 992px for tablets, 992px to 1200px for medium screens, and above 1200px for large screens like Apple retina and 4K.

To achieve this, you can create classes such as .show-sm and .hidden-sm for your specific needs:

For displaying an element only on mobile:

@media screen and (max-width: 768px) {
    .hidden-sm {
        display: none !important;
    }
    .show-sm {
        display: block !important;
    }
}

For displaying an element above the mobile resolution:

@media screen and (min-width: 768px) {
    .hidden-sm {
        display: block !important;
    }
    .show-sm {
        display: none !important;
    }
}

You can then apply these classes to the elements you want to hide or show on mobile or desktop.

Additionally, you can create custom media queries for specific resolutions:

@media screen and (min-width: 768px) and (max-width: 992px) {
    .hidden-md {
        display: none !important;
    }
}

Remember to include a viewport meta tag in your HTML head for better responsiveness:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using the <noscript> tag for an individual element or a comparable alternative

So, I have a link labeled "Impressum" that when clicked, opens up the Impressum section. <a data-open="something">Impressum</a> <div class="reveal" id="something" data-reveal> <img src="images/reverseLogo.png"> <h1>Imp ...

Unable to get font-face to function properly on IE versions 7 and 8

I'm having trouble getting the font-face to work properly on both IE7 and IE8. This is the code snippet I have used: @font-face { font-family: 'DroidSans'; src: url('fonts/DroidSans.eot'); src: url('fonts/DroidSa ...

Could you advise on the best placement for my upcoming JQuery animation?

Here is the code I am currently working with: $(function() { $("button").click(function() { $("#box1").animate({ left: $(window).width() - 800 }, { complete: function() { $("#box1").hide(); } }); $("#box2").a ...

Change the background color with a click in HTML

Is it possible to include two onclick arguments in a button tag like this: <div id="Spacer" align="center"> <button id="button" onclick="document.getElementById('pop').style.display='block';$('#grayout').toggle ...

Tips on adjusting sticky behavior for responsiveness using bootstrap-4

In my project, I am utilizing angular with bootstrap. The header of the project consists of two parts and a content area. However, when the resolution is small, the header wraps. Check out the header and content on large screens View the header and conte ...

Executing JavaScript after jQuery and the DOM have completed loading in C#

Within my asp.net/c# project, I am incorporating the jquery library using the following code snippet: <SharePoint:ScriptLink ID="jquery_js" name="/_layouts/PDF Library/jquery-1.10.1.min.js" runat="server" OnDemand="False" Localizable="False" /> Now ...

The Fab Button from Material UI remains beneath the left split-pane

Is there a way to ensure the Fab button is completely visible? The left side often gets hidden under the left pane. I attempted to increase the z-index, but it did not have any effect. View on CodeSandbox <UpperPane> <Fab ...

When the checkbox is not selected, the content on the page will revert back to its original state

Is there a way to dynamically change content on a page when a checkbox is checked, and revert it back when the checkbox is unchecked? I don't want to manually set each element's value to default in JavaScript and CSS. <div class="switch&q ...

What are some methods for customizing the calendar icon displayed in an input field with type date?

Is there a way to customize the calendar logo without relying on jquery? The desired appearance should resemble the image shown below: https://i.sstatic.net/G06iZ.png input { width: 50%; padding: 8px; border-radius: 10px; ...

What is causing the discrepancy in state/CSS transition times for this basic ReactJS slider?

If you're interested, I made a functional demo sandbox which can be found here This particular demo showcases a basic array cycler with 3 elements that are displayed as slides moving left or right depending on the selected direction. While I acknowl ...

Box-Shadow malfunctioning on Mozilla Firefox

My CSS code is not displaying the shadow effect in Mozilla Firefox: body { text-align: center; font-family: Sans-serif; background-image: url("d3.jpg"); background-repeat: no-repeat; background-attachment: fixed; background-size: c ...

The error message fails to display a second time unless the page is refreshed when validating with Ajax submission

The message "(#errmsg)" is not displaying the second time without refreshing the page when validating using Ajax submission. <div class="col-md-2"> <input type="text" id="pay_containt" maxlength='51' class="form-control" name ...

Adjust the width of the button to best fit the content or label

Here we have a screenshot of HTML source code showing a button that is wider than the content it contains. The highlighted area in yellow indicates there is extra space at the right side of the button due to it being displayed on multiple lines. Is this be ...

Can you determine the exact spot in a paragraph where a mouse click event takes place?

My webpage has a section with a paragraph containing text. If the user clicks on the paragraph, a textarea is dynamically created with the same text from the paragraph. I am wondering if there's a way to determine the exact location within the paragra ...

What could be the reason why my hx-trigger isn't activated when using the "from: <css selector>" option?

I am facing an issue with sending multiple requests to the server when clicking a button. The structure is as follows: <button id="add-item" hx-get="some-url" hx-trigger="click" hx-target="#item-form" hx-swap=&quo ...

What is the best way to ensure that the input search bar, microphone icon, and two small boxes adapt to different screen

Upon submitting my exercise for The Odin Project, I was under the impression that everything looked perfectly aligned and centered on my MacBook Pro 15-inch screen. However, when I viewed the completed webpage on a larger computer screen at work, I noticed ...

What is the best way to ensure a logo image is properly scaled to fit its parent container using Bootstrap 4

I am struggling with my navigation bar, which consists of a simple logo and a few links. The issue I am facing is that the logo image is too tall for the parent container, which has a fixed height. It's clear that the logo with the gray background e ...

Modifying the Button component does not affect the hover color

I'm currently attempting to modify the color of all the buttons in my project by overriding the theme CSS. Although I successfully changed the button color, the hover color remains transparent. Any suggestions on how to override this? Are there any a ...

Adding an HTML string to the head in Next.js

Every time I fetch data from an API, it returns an object with the property head: '<title>dummy title<title>' Despite trying different methods, I am unable to display this HTML string in the head tag. This is my code: <Head>{da ...

Creating Dynamic Web Design: Horizontal Scrolling Window and Adaptive HTML Content

After spending countless hours researching online, I am still unable to find a solution for responsive web design that maintains the aspect ratio of both the window and HTML body. Here are examples of what I'm looking for: original view, stretched le ...