skip to Main Content

I am trying to make a homepage of some sorts and I can’t find a way to make a div center, I can’t really explain it good so the picture might help
The piece of code I’m trying to fix

I tried putting text-align: center; for the div but it only centered the text in the div, I wanted it to center the div just like the text above.

HTML:
<script src="https://kit.fontawesome.com/0c86b13d40.js" crossorigin="anonymous"></script> <div> <p class="text title">My Info</p> </div> <div id="buttons"> <i class="fa-solid fa-house"> H o m e </i> </div>

CSS:

    .title {
      font-size: 350%;
      margin-top: 100px;
    }

    .text {
      text-align: center;
    }

    #buttons {
      text-align: center;
      width: 130px;
      border: 2px solid;
      padding: 10px;
      border-radius: 25px;
    }

4

Answers


  1. You can use the flex display property.
    Wrap the buttons inside a div set to flex:

    <div id='flex'>
      <div>Buttons div go in here</div>
    </div>
    

    Then use this CSS:

    div#flex {
      display: flex;
      justify-content: center;
    }
    

    FYI text-align only works on content within the div itself.

    Login or Signup to reply.
  2. You used the text-align propoerty which centers text only;
    You should use the follow css to center elements:

    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    

    it’ll center your elements both vertically and horizontally.

    Login or Signup to reply.
  3. CSS property margin: 0 auto; can be used to center a div horizontally. By setting the left and right margins to auto, the div will be centered horizontally within its parent container.

    <div style="border: 1px solid black; width: 200px; margin: 0 auto; text-align: center;">
       <i class="fas fa-home"></i>
       <p>Some text</p>
    </div>
    

    HTML Code snippet

    Login or Signup to reply.
  4. It might be because they are not inside the same div?
    It would be helpful if you could upload some code here but this code works too.

    <!DOCTYPE html>
    <html lang="en-us">
    <head>
       <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    </head>
    
    <style>
      button {
        width: 200px;
        padding: 5px;
        background-color: lightcoral;
        border-radius: 5px;
        color: white;
        font-size: 20px;
      }
      button:hover {
        background-color: lightblue;
      }
      div {
        text-align: center;
      }
    </style>
    
    <body>
    <div> 
      <p>hello world</p>
      <button> <i class="fa fa-car"></i></button>
      </div>
      
        </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search