How to center the second inline-block element with CSS

Viewed 48

I want my first element to be on the left and my second element to be in the exact center of the screen (while being horizontally aligned). Logo/text left, navigation bar in the middle.

I cant seem to get the following result with the code below:

|red|-------|green|------------|

I want the center of the Green square in the middle of the screen. Which would normally happen if I used text-align: center; on a single element if its not inline-blocked.

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;
      }

Would really appreciate any advice, I have been stuck on this for a few days now already. I've tried to wrap them both up in a div and text-align: center; them. but then I cant seem to push the red square back to the left.

And while I can do it by playing with the margins and eyeballing the center, this does not feel like the optimal solution.

2 Answers

<!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 can use flexbox to adjust elements accordingly. I created a main-div then gave height and width and then its has green and red div's , I applied flex property to main and gave width to each div so , by adjusting the width u can change the position of logo or navbar.

<!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>
Related