What is the best way to combine percentage and pixel values for setting a max-width?

Is there a way to limit the width of a div so that it does not exceed either a percentage or pixel value? I want the browser to calculate the pixel equivalent of the percentage and then choose the smaller value.

For example, if I set both values like this:

{max-width:100px; max-width:20%;}
, the browser will prioritize the second value and disregard the first one.

Answer №1

width:20%;
max-width:100px;

By using this code snippet, the width is constrained to 20% but will not exceed 100 pixels.

Answer №2

To achieve this goal, a simple solution would be to utilize a combination of two separate div elements.

<div class="container">
  <div class="box">
    The text inside will not surpass a width of 100 pixels or 20% of the total container.
  </div>
</div>

<style>
.container {
  max-width: 90%;
}
.box {
  max-width: 100px;
}
</style>

Answer №3

CSS min() function is now available for use, however, it's important to remember that Internet Explorer does not support this feature.

width: min(20%, 100px)

Learn more about CSS min() function here.

Answer №4

When working with images of various sizes and aspect ratios, it's important to note that this method may not be suitable. It is possible to specify different max-width and max-height values individually if you have knowledge of the image dimensions. This technique is best used for a specific set of images rather than as a universal solution.

For example, let's say you have 5 photos from your phone that you want to display on a webpage alongside some text. You resize the images to 500px wide and 300px high. To ensure they do not take up more than half of the screen or exceed a width of 250px on a tablet, you can calculate the maximum height using the formula: 250*300/500=150px.

.img-class {
    max-width: 50%;
}
@media (max-width: 800px) {
    .img-class {
       max-height: 150px;
    }
}

This method has been tested on the latest versions of Chrome, Firefox, and Internet Explorer.

Answer №5

I encountered a unique issue that needed a creative solution. My goal was to showcase all images in their original size without constraints on aspect ratio, alignment, or additional HTML elements, while also ensuring they do not exceed a specified maximum width in pixels. If the viewport is smaller than this designated size, the images should dynamically adjust. Simply setting a width property would not suffice for my requirements.

Building upon @Kiaurutis' suggestion:

img {
  max-width: 400px;
}

@media (max-width: 400px) {
  img {
    max-width: 100%;
  }
}

You can see a functional demonstration here: https://jsfiddle.net/vrehxmpx/. In the provided example, an image larger than 400px will always scale down accordingly, while an image smaller than the threshold will only resize if the screen reduces below the image's dimensions.

To account for margins, borders, and other decorative elements surrounding the image, simply modify the @media's max-width value.

Answer №6

Avoid this practice.

In my opinion, the answer chosen seems to be suitable for the situation described by the original poster (OP). However, there are some comments suggesting that the OP wants the max-width property to be set as the smaller value, not the width. This alternative approach can also be applied, as shown below.

Important: Personally, I find this solution a bit confusing. It is recommended to follow the selected answer, which effectively illustrates the purpose of max-width. The code snippet provided ensures that the max-width will be restricted to either 20% or 100px (whichever is lower).

img {
    max-width: 20%;
}

@media (min-width: 500px){ /* When the viewport width reaches 500 pixels, 20% equals 100px */
    img {
        max-width: 100px;
    }
}

Answer №7

On my website, I had a page wrap with the same width setting. My goal was to have it default to 95% width but not exceed 1280px in size. This is how I accomplished it through CSS:

.wrap{max-width:95%;margin:0px auto;}
@media screen and (max-device-width:1280px),screen and (max-width:1280px){.wrap{max-width:1280px;margin:0px auto;}}

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

How to create an image overlay in Angular with the help of Bootstrap

As a beginner in web development, I am utilizing Angular in conjunction with Bootstrap for a practice project. My goal is to create a header component and integrate it into my app.component. Within the app.component, I aim to have a background image coveri ...

How to implement a scrollbar for tables using Angular

How can I implement a vertical scroll bar only for the table body in my Angular code? I want the scroll bar to exclude the header rows. Since all rows are generated by ng-repeat, I am unsure how to add overflow style specifically for the table body. Here ...

`The functionalities of classList.add and classList.remove aren't behaving as anticipated.`

I'm currently working on a list of items (ul, li) that have a class applied to them which adds a left border and bold highlight when clicked. My goal is to reset the style of the previously clicked item back to its original state when a new item is c ...

PHP Debate: Static vs Non-Static - Which is the Superior Choice?

Static and non-static functions as well as class properties really had me puzzled when I attempted to launch my website. Could someone clarify whether it is preferable to have the entire website coded using static functions rather than relying on non-stat ...

The navigation bar is not showing up at the top of my webpage as expected, instead, it is displaying

1 I attempted to build a model Google site to enhance my HTML and CSS skills, but I encountered an unusual issue where my navigation menu is showing up inside my image div, even though it was created before that. I have given backgrounds to the navs and i ...

What is the best way to temporarily lock a section's position on a page?

I'm interested in learning how we can keep a particular section fixed in position temporarily, similar to the example provided below. In the link above, the Apple Watch product remains fixed while the content on the right side moves slightly before t ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Position the current div in the center of a bootstrap progress bar for mobile devices

I'm facing an issue with the bootstrap progress bar on my website, especially on mobile devices where it goes off the screen. I want the current page marker on the progress bar to be centered on the screen while allowing the bar to extend beyond the s ...

What can you tell me about creating a dropdown tree combo box using JavaScript?

Upon reviewing my work, I noticed that the sequence of the drop-down boxes has been inadvertently reversed. This is not aligned with the desired outcome. How can I utilize a method to ensure that the order of the drop-down boxes is correct? However, this ...

Why won't the audio tag play any audio on IE10 Windows7?

Encountering issues with the audio tag on Internet Explorer 10/Windows 7. Discovered a test page where IE is unable to display any audio tags. Interestingly, when the file is saved and tested locally, it works perfectly (see image below). Confirming that ...

"Enhance your HTML table by selecting and copying cell values with a simple click and CTRL +

I stumbled upon a fantastic script for highlighting HTML table rows and it's working perfectly: I decided to modify the onclick event to onmouseover and included additional code to select a cell by clicking on it. Now I can select, check which one is ...

Validation for checkbox completeness is not functioning as expected

I am attempting to create a function that checks if all checkboxes are checked and then changes the class of a button accordingly. However, my code does not seem to be functioning as expected and I am unsure why. <input type="checkbox" id="check1" onch ...

AJAX code fetching dynamic content without relying on file loading

When I load my program, the dynamic code does not appear on the page until I reload it again. I attempted to use the onload event in the body to load content from an XML file using AJAX, but it only works after closing and reopening the program, not dynam ...

Tips for targeting a specific set of elements in codeBehind within Web Forms without creating an additional wrapper element

In my Webform page, I have a html form containing fields for customer data and product data, as well as other miscellaneous fields. I am facing the challenge of needing to hide either the group of product fields or customer fields during PageLoad or other ...

Exploring robot framework methods for class verification

Are there any specific keywords in Robot Framework that can be used to verify if an element has a particular class assigned to it? Perhaps something like Element should have class element className Or I could also check if the element has a specifi ...

The footer is refusing to show up at the bottom of the page

Why is my footer floating in the middle of the page? It's driving me crazy. I really hope it's a quick fix. I've searched online and all the solutions point to having a fixed footer, but I don't want that because it looks bad on smaller ...

What could be causing my HTML to not display properly after making changes to a text node?

Can a DOM text node be altered in such a way: node.nodeValue = "foo <strong> bar </strong>" so that it displays the HTML correctly? Appreciate any help. ...

ColorBox refuses to adjust width dynamically

Utilizing the Jquery plugin called colorbox in my HTML application has presented me with a challenge. I have two divs on my page – one positioned at the left and the other at the right. What I desire is for the right div to initially have its display set ...

Repeat the execution or refresh an EventListener

I am a beginner in the world of coding, currently working on my inaugural project to create a web-based game using HTML, CSS, and JavaScript. I have encountered an issue with the .addEventListener() method that I couldn't seem to find a solution for ( ...

The static page is missing the favicon icon

For the past four days, I've been diving into the world of HTML and CSS to create my own personal webpage. As a beginner, I haven't yet hosted it and am still in the process of crafting it. One thing I attempted was designing a favicon for my sit ...