AmenomoriYuuna
有两个div在header这个div里,header是100%宽度,小div1我希望它靠左以便用于网页的标题,而小div2我希望它相对于整个header是居中的

但由于div1的存在好像让div2总是偏右,该如何让div2在正中央呢

Lidocaine
参考下述代码
  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Test</title>
  6.     <style>
  7.         body{
  8.             text-align: center;
  9.         }
  10.         header {
  11.             width: 100%;
  12.             background-color: yellow;
  13.         }

  14.         .div1 {
  15.             background-color: green;
  16.             width: 80px;
  17.             float: left;
  18.             /*  把div1固定在左侧  */
  19.         }

  20.         .div2 {
  21.             width: 80px;
  22.             background-color: red;
  23.             margin: auto;
  24.             /*  把div2居中显示 */
  25.         }
  26.     </style>
  27. </head>
  28. <body>
  29. <header>
  30.     <div class="div1">测试Div</div>
  31.     <div class="div2">测试Div</div>
  32. </header>
  33. </body>
  34. </html>
复制代码

0o酱
本帖最后由 0ojixueseno0 于 2022-3-28 08:35 编辑



  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=100%, initial-scale=1.0">
  7.     <title>Document</title>
  8.     <style>
  9.         * {
  10.             margin: 0 auto;
  11.             color: white;
  12.         }
  13.         .header {
  14.             width: 100%;
  15.             height: 100px;
  16.         }
  17.         .div1 {
  18.             width: 500px;
  19.             position: absolute;
  20.             top: 0;
  21.             left: 0;
  22.             background-color: blueviolet;
  23.         }
  24.         .div2 {
  25.             width: 500px;
  26.             background-color: red;
  27.         }
  28.     </style>
  29. </head>
  30. <body>
  31.     <div class="header">
  32.         <div class="div1">这是Div1的内容</div>
  33.         <div class="div2">这是Div2的内容</div>
  34.     </div>
  35. </body>
  36. </html>
复制代码


mcbbs里问前端问题真的没问题吗hhhhhh

Craftwolves
设置header为相对定位,div2为绝对定位,然后将div2居中

AmenomoriYuuna
Craftwolves 发表于 2022-3-28 10:17
设置header为相对定位,div2为绝对定位,然后将div2居中

虽然参考了其他方法【新增了一个div和div1一样宽然后放在右边了】
非常感谢