有两个div在header这个div里,header是100%宽度,小div1我希望它靠左以便用于网页的标题,而小div2我希望它相对于整个header是居中的
但由于div1的存在好像让div2总是偏右,该如何让div2在正中央呢
但由于div1的存在好像让div2总是偏右,该如何让div2在正中央呢
参考下述代码
复制代码
- <!DOCTYPE html>
- <html lang="zh">
- <head>
- <meta charset="UTF-8">
- <title>Test</title>
- <style>
- body{
- text-align: center;
- }
- header {
- width: 100%;
- background-color: yellow;
- }
- .div1 {
- background-color: green;
- width: 80px;
- float: left;
- /* 把div1固定在左侧 */
- }
- .div2 {
- width: 80px;
- background-color: red;
- margin: auto;
- /* 把div2居中显示 */
- }
- </style>
- </head>
- <body>
- <header>
- <div class="div1">测试Div</div>
- <div class="div2">测试Div</div>
- </header>
- </body>
- </html>
本帖最后由 0ojixueseno0 于 2022-3-28 08:35 编辑

复制代码
mcbbs里问前端问题真的没问题吗hhhhhh

- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=100%, initial-scale=1.0">
- <title>Document</title>
- <style>
- * {
- margin: 0 auto;
- color: white;
- }
- .header {
- width: 100%;
- height: 100px;
- }
- .div1 {
- width: 500px;
- position: absolute;
- top: 0;
- left: 0;
- background-color: blueviolet;
- }
- .div2 {
- width: 500px;
- background-color: red;
- }
- </style>
- </head>
- <body>
- <div class="header">
- <div class="div1">这是Div1的内容</div>
- <div class="div2">这是Div2的内容</div>
- </div>
- </body>
- </html>
mcbbs里问前端问题真的没问题吗hhhhhh
设置header为相对定位,div2为绝对定位,然后将div2居中
Craftwolves 发表于 2022-3-28 10:17
设置header为相对定位,div2为绝对定位,然后将div2居中
虽然参考了其他方法【新增了一个div和div1一样宽然后放在右边了】
非常感谢