左右宽度固定中间内容自适应html布局的三种方法

一时失言乱红尘 2022-01-31 12:15 409阅读 0赞

牛客网的一道面试题,要求左右宽度固定中间自适应,如下图的布局方式
在这里插入图片描述
一、弹性布局
父元素display:flex子元素会全部并列在一排。
子元素中flex:n的宽度会将父元素的宽度/n
如flex:1,宽度就等于父元素宽度。

  1. *{
  2. margin: 0;
  3. padding: 0;
  4. text-align: center;
  5. font-size: 25px;
  6. color: white;
  7. line-height:100px;
  8. }
  9. .header{
  10. width: 100%;
  11. height: 100px;
  12. background-color: #7ecef3;
  13. }
  14. .center{
  15. display: flex;/ !
  16. }
  17. .content{
  18. background-color: #53b9b1;
  19. flex:1;/ !
  20. }
  21. .left_bar{
  22. height: 700px;
  23. width: 200px;
  24. background-color: #89c997;
  25. }
  26. .right_bar{
  27. width: 200px;
  28. background-color: #89c997;
  29. }
  30. .footer{
  31. width: 100%;
  32. height: 100px;
  33. background-color: #7ecef3;
  34. }
  35. <div class="header">header</div>
  36. <div class="center">
  37. <div class="left_bar">left_bar</div>
  38. <div class="right_bar">right_bar</div>
  39. <div class="content">content</div>
  40. </div>
  41. <div class="footer">footer</div>

二、absolute相对定位

  1. .header{
  2. width: 100%;
  3. height: 100px;
  4. background-color: #7ecef3;
  5. }
  6. .center{
  7. position: relative;
  8. }
  9. .content{
  10. background-color: #53b9b1;
  11. position: absolute;/ !
  12. left: 200px; !
  13. right: 200px;// !
  14. height: 500px;
  15. }
  16. .left_bar{
  17. width: 200px;
  18. position: absolute;
  19. left: 0;
  20. background-color: #89c997;
  21. height: 500px;
  22. }
  23. .right_bar{
  24. width: 200px;
  25. background-color: #89c997;
  26. position: absolute;
  27. right: 0;
  28. height: 500px;
  29. }
  30. .footer{
  31. width: 100%;
  32. height: 100px;
  33. background-color: #7ecef3;
  34. position: absolute;
  35. bottom: 0;
  36. }

三、float浮动,加margin-left、margin-right

  1. .header {
  2. width: 100%;
  3. height: 100px;
  4. background-color: #7ecef3;
  5. }
  6. .left_bar {
  7. width: 200px;
  8. background-color: #89c997;
  9. float: left;
  10. height: 500px;
  11. }
  12. .right_bar {
  13. width: 200px;
  14. background-color: #89c997;
  15. float: right;
  16. height: 500px;
  17. }
  18. .content {
  19. background-color: #53b9b1;
  20. margin-left: 200px;/ !
  21. margin-right: 200px;/ !
  22. height: 500px;
  23. }
  24. .footer {
  25. width: 100%;
  26. height: 100px;
  27. background-color: #7ecef3;
  28. }

浮动时注意先后顺序,否则会达不到效果

  1. <div class="left_bar">left_bar</div>
  2. <div class="right_bar">right_bar</div>
  3. <div class="content">content</div>

发表评论

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

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

相关阅读