简体   繁体   中英

How to prevent min-width overriding max-width?

I've created a div that i want to be 50% (for arguments sake) but at least a certain width and at most 100% width, (so that it never extends the window)

.about {
    position:absolute;
    right:0;
    width: 50%;
    min-width: 500px;
    max-width: 100%;
}

Basically, i want the min-width to work, but i want the max-width to be considered MORE important so that it is never wider than the window, i assumed that i could do this by the order, or at least by using !important, but this doesn't seem to be the case

https://jsfiddle.net/ex716kam/2/

I've given it a few tries but I can't seem to make it work with CSS alone. I would recommend using simple javascript or media queries to make it work.

Working jsFiddle

@media screen and (min-width:1000px){
    .about{
        width:50%;
    }
}

Note what @lmgonzalves wrote about min-width being the "strongest"..

Just switch the values of min-width and width:

.about {
    position:absolute;
    right:0;
    width: 500px;
    min-width: 50%;
    max-width: 100%;
}

https://jsfiddle.net/8fkbp9d0/

Instead of max-width: 100%; use max-width:100vw; . It will not go out of your window.

It's difficult to know what behaviour you expect between 1000px down to 500px, but a media query is the simplest way to achieve what you're looking for:

 .about { position:absolute; right:0; width: 50%; min-width:500px; } @media screen and ( max-width: 500px ){ .about { width: 100%; min-width:0; } } 
 <div class="about"> <h1>About</h1> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </div> 

try this code, this code will work when screen width will be between 500px to 100% screen resolution.

@media (min-width: 500px) and (max-width: 800px)
{
.about {
        position:absolute;
        right:0;
        width: 50%;
    }
}

min() function does the trick. Insert your max-width as an argument. This way min-width can never be wider than your max-width

min-width: min(500px, 100%);
max-width: 100%;

Currently supported in all major browsers except IE: caniuse.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM