问题:若两个内层盒子宽度设定为50%,则加上间隔15px会超出父容器就会自动换行;若两个内层盒子宽度设定为小于50%,则浏览器尺寸改变时就不会充满父容器,导致水平不居中。
解决方法:使用calc()动态计算宽度。(注意运算符前后都需要保留一个空格;支持“+,-,*,/”运算,遵循标准数学运算优先级规则)
width: calc((100% - 15px) * 0.5);
实例 :
代码:
Float
*{
margin: 0;
padding: 0;
font-family: arial;
color: #777;
}
.container{
width: 70%;
margin: 50px auto;
}
.container::after{
content: "";
display: block;
clear: both;
}
.item:nth-child(1){
margin-right: 15px;
}
.item{
float: left;
width: calc((100% - 15px) * 0.5);
background: #eee;
box-shadow: 2px 2px 10px 0 rgba(0,0,0,0.15);
}
.item:hover{
box-shadow: 4px 4px 20px 0 rgba(0,0,0,0.20);
}
h2,p{
margin: 15px;
}
p:first-letter{
font-size: 1.5em;
}
HTML
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos molestiae dolore doloribus eaque error quasi suscipit neque eius quidem hic adipisci dolor quo qui blanditiis voluptates fugit pariatur incidunt impedit.
CSS
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Magnam iste obcaecati vitae amet ab quae libero ut recusandae laudantium aliquid dignissimos nihil perspiciatis ipsum quisquam temporibus qui maxime porro ex.
作者:KRISLEE1