详解左右宽度固定中间自适应html布局解决方案

青旅半醒 2021-11-01 19:52 398阅读 0赞

a.使用浮动布局
html结构如下

  1. <div class="box">
  2. <div class="left">left</div>
  3. <div class="right">right</div>
  4. <div class="center">center</div>
  5. </div>
  6. //此处注意要先渲染左、右浮动的元素才到中间的元素。元素浮动后剩余兄弟块级元素会占满父元素的宽度
  7. <style>
  8. .box{
  9. height:200px;
  10. }
  11. .left{
  12. float:left;
  13. width:300px;
  14. }
  15. .right{
  16. float:right;
  17. width:300px;
  18. }
  19. </style>

b.使用固定定位
html结构如下

  1. <div class="box">
  2. <div class="left">left</div>
  3. <div class="right">right</div>
  4. <div class="center">center</div>
  5. </div>
  6. //和浮动布局同理,先渲染左右元素,使其定位在父元素的左右两端,剩余的中间元素占满父元素剩余宽度。
  7. <style>
  8. .box{
  9. position: relative;
  10. }
  11. .left{
  12. position: absolute;
  13. width: 100px;
  14. left: 0;
  15. }
  16. .right{
  17. width:100px;
  18. position: absolute;
  19. right: 0;
  20. }
  21. .center{
  22. margin: 0 100px;
  23. background: red;
  24. }
  25. </style>

c.表格布局
将父元素display:table,子元素display:table-cell,会将它变为行内块。
这种布局方式的优点是兼容性好。

  1. <div class="box">
  2. <div class="left">
  3. left
  4. </div>
  5. <div class="center">
  6. center
  7. </div>
  8. <div class="right">
  9. right
  10. </div>
  11. </div>
  12. <style>
  13. .box{
  14. display: table;
  15. width: 100%;
  16. }
  17. .left{
  18. display: table-cell;
  19. width: 100px;
  20. left: 0;
  21. }
  22. .right{
  23. width:100px;
  24. display: table-cell;
  25. }
  26. .center{
  27. width: 100%;
  28. background: red;
  29. }
  30. </style>

d.弹性布局
父元素display:flex子元素会全部并列在一排。
子元素中flex:n的宽度会将父元素的宽度/n
如flex:1,宽度就等于父元素高度。
弹性布局的缺点是兼容性不高,目前IE浏览器无法使用弹性布局

  1. <div class="box">
  2. <div class="left">
  3. left
  4. </div>
  5. <div class="center">
  6. center
  7. </div>
  8. <div class="right">
  9. right
  10. </div>
  11. </div>
  12. <style>
  13. .box{
  14. display: flex;
  15. width: 100%;
  16. }
  17. .left{
  18. width: 100px;
  19. left: 0;
  20. }
  21. .right{
  22. width:100px;
  23. }
  24. .center{
  25. flex:1;
  26. }
  27. </style>

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,398人围观)

还没有评论,来说两句吧...

相关阅读