标准盒子模型box-sizing: border-box; 宽度=内容的宽度(content)+ border + padding + margin
低版本IE盒子模型:宽度=内容宽度(content+border+padding)+ margin
通过属性box-sizing进行区分,标准盒模型box-sizing为默认值:content-box; 低版本IE盒子模型box-sizing:border-box
如以下整个区域分为外面的边框和绿色框的商品展示区。外面的边框区域宽高固定。如果想要让绿色框的商品展示区随着外面的边框的宽高自适应,就可以设置父级容器box-sizing: border-box;子级设置width和height为100%即可。这个是外部宽高固定的情况下
如果宽高不固定就可以使用标准盒模型
布局的传统解决方案,基于盒状模型,依赖 display属性 + position属性 + float属性。它对于那些特殊布局非常不方便,比如,垂直居中就不容易实现。
横向:子元素中display:inline-block或者float浮动,或者定位
横向居中:父级元素中使用text-align:center
注意定位一般能不用就不用,因为定位布局会脱离文档流
子元素使用display: inline-block;vertical-align: middle; 父元素使用text-align: center; line-height: 元素高度
注意:ertical-align: middle必须设置在子元素中
- <style>
- .parent {
- width: 400px;
- height: 400px;
- background-color: gray;
- margin: 0 auto;
- line-height: 400px;
- text-align: center;
- }
-
- .child {
- width: 200px;
- height: 200px;
- background-color: aqua;
- display: inline-block;
- /* 注意垂直居中设置在子元素中 */
- vertical-align: middle;
- }
- style>
- head>
- <body>
- <div class="parent">
- <div class="child">div>
- div>
- body>
知道宽高情况下:父元素相对定位,子元素绝对定位;left:50%和top:50%; margin-top:负子元素高度一半;margin-top:负子元素宽度一半;
不知道宽高时:使用transform。父元素相对定位,子元素绝对定位;left:50%和top:50%; transform: translate(-50%,-50%)
- <style>
- .parent {
- width: 400px;
- height: 400px;
- background-color: gray;
- margin: 0 auto;
- position: relative;
- }
-
- .child {
- width: 200px;
- height: 200px;
- background-color: aqua;
- position: absolute;
- top:50%;
- left: 50%;
- /* transform: translate(-50%,-50%); */
- margin-top: -100px;
- margin-left: -100px;
- }
- style>
- head>
-
- <body>
- <div class="parent">
- <div class="child">div>
- div>
- body>
- /*加一个四色的正方形*/
- width: 100px;
- height: 100px;
- border-top: 1px solid purple;
- border-left: 1px solid orange;
- border-right: 1px solid blue;
- border-bottom: 1px solid #ff0000;
- /*四个三角形*/
- width: 0;
- height: 0;
- border-top: 100px solid purple;
- border-left: 100px solid orange;
- border-right: 100px solid blue;
- border-bottom: 100px solid #ff0000;
-
- /*元素宽度和高度设置为0,设置一个边框为元素宽度一样,给其他三边边框颜色设置为透明属性transparent,就能形成三角形*/
- width: 0;
- height: 0;
- border-top: 100px solid transparent;
- border-left: 100px solid transparent;
- border-right: 100px solid transparent;
- border-bottom: 100px solid #ff0000;