简体   繁体   中英

Css max-width not working as expected in div

I have an HTML structure like:

 .container { width: 100%; height: 300px; background-color: blue; } .dots-container-wrapper { width: 100%; } .dots-container { max-width: 55px; overflow: hidden; min-width: 1px; display: block; padding: 0; margin: 0 auto; height: 0.875rem; position: relative; } .dots-container>ul { padding: 0; display: flex !important; transition: all 0.25s; position: relative; margin: 0; list-style: none; transform: translateX(0); align-items: center; bottom: unset; height: 100%; } .dots-container>ul li { width: 6px; height: 6px; margin: 0 2.5px; background-color: #fff; border: none; border-radius: 50%; display: inline-block; opacity: .7; }
 <div class="container"> <div class="dots-container-wrapper"> <div class="dots-container"> <ul class="dots"> <li></li> <li></li> </ul> </div> </div> </div>

The problem is that the div "dots-container" has a property max-width: 55px. But in case the width is less than 55px, I would like to use the real width, however, the div is always 55px. This is a problem because I´m using this in a carousel with dots functionality. When there are 5 pictures, you can see 5 dots aligned in the center, but in case there are fewer pictures, let´s say 2, the div is still 55px and the dots don´t seem to be aligned in the center. See example screenshots.

在此处输入图片说明

在此处输入图片说明

Your .dots-container is displayed as a block. By default a block will always try to fill up the entire width. By making the container .dots-container-wrapper display flex, it's children will only take up as much space as they need (while also centering them if needed).

.dots-container-wrapper {
    width: 100%;
    display: flex; // change to flex
}

.dots-container {
    max-width: 55px;
    overflow: hidden;
    min-width: 1px;
    display: block;
    padding: 0;
    margin: 0 auto;
    height: 0.875rem;
    position: relative;
}

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