如何使用CSS居中第二个inline-block元素



我想让我的第一个元素在左边,我的第二个元素在屏幕的正中央(同时水平对齐)。Logo/文字左边,导航条在中间。

使用下面的代码,我似乎无法得到以下结果:

红色| | - - - |绿色 |------------|

我想绿色广场的中心屏幕中间的. 如果我使用text-align: center;

HTML:

<body>
<div class="red-color"></div>
<div class="green-color"></div>
</body>

CSS:

.red-color {
background-color: red;
padding: 100px;
display: inline-block;
}
.green-color {
background-color: green;
padding: 100px;
display: inline-block;
}
我真的很感激任何建议,我已经在这个问题上困了好几天了。我试着用div和text-align: center;他们。但是我似乎不能把红色方块推回左边。

虽然我可以通过玩边距和目测中心来做到这一点,但这并不是最佳解决方案。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.main{
width: 100%;
height: 100px;
display: flex;
flex-direction: row;

}
.red-color {
background-color: red;
width: 30%;
}
.green-color {
background-color: green;
width: 30%;
}
</style>
<body>
<div class="main">
<div class="red-color">logo/text</div>
<div class="green-color">navbar</div>
</div>

</body>
</html>

u可以使用flexbox进行相应的元素调整。我创建了一个main-div,然后给出了高度和宽度,然后它有绿色和红色的div,我给main应用了flex属性,给每个div的宽度,所以,通过调整宽度,你可以改变logo或导航条的位置。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">`enter code here`
<title>Document</title>
</head>
<style>
.main{
width: 100%;
height: 100px;
display: flex;
flex-direction: row;

}
.red-color {
background-color: red;
width: 30%;
margin-right: 5%;
}
.green-color {
background-color: green;
width: 30%;
margin-left: 10%;
}
</style>
<body>
<div class="main">
<div class="red-color">logo/text</div>
<div class="green-color">navbar</div>
</div>

</body>
</html>

最新更新