【HTML+CSS】ul中li水平居中,可以根据media查询,不同个数的li水平居中

通过计算给ul设置宽度width,来控制页面每行显示几个li,且li水平居中显示的,具体的间距通过li的margin来设置:

注:图片格式为240*240,span和div文字为图片详情描述,在图片下面显示;

.fdProduct-layout-content {
    width: 100%;
    margin: 0 auto;
}

.fdProduct-layout-content ul{
    width: 520px;
    margin: 0 auto;
    overflow: auto;
}

.fdProduct-layout-content ul li {
    width: 220px;
    /*margin上右下左*/
    margin: 20px;
    float: left;
    word-break: break-all;
    word-wrap: break-word;
}

.fdProduct-layout-content li span {
    font-weight: bold;
    line-height: 24px;
    font-size: 1.4rem;
    color: red;
}

/*li三列显示*/
@media screen and (min-width:780px) and (max-width:960px){
    /*780计算方法:每个img220+左右间距各20 (220+20+20)*3 */
    .fdProduct-layout-content ul{
        width: 780px;
        margin: 0 auto;
    }
}

/*li四列显示*/
@media screen and (min-width:960px) and (max-width:991px){
    /*960计算方法:每个img220+左右间距各10 (220+10+10)*4 */
    .fdProduct-layout-content ul{
        width: 960px;
        margin: 0 auto;
        overflow: auto;
    }
    .fdProduct-layout-content ul li {
        width: 220px;
        margin: 10px;
        float: left;
        word-break: break-all;
        word-wrap: break-word;
    }
}

其他多少个li的个数居中显示,根据需要来,主要在ul的宽度设置和li的margin调节;

计算方法:

    (img的像素+margin左右间距)*每行显示多少个li

一个很有趣的做法:

打开浏览器调试模式,调整ul的宽度width,用滚轮,可以测试出ul的宽度来。

挺好用的!因为可能你的li需要设置padding;这样就可以不用计算了~

加油,多思考,多尝试,不骄不躁,一切问题都可以解决,还有沟通很重要~

你可能感兴趣的:(HTML+CSS)