Home > Blockchain >  CSS / HTML: How to center div horizontally?
CSS / HTML: How to center div horizontally?

Time:01-23

I know this question has been asked hundreds of times, but for some reason I cant get it to work. Both my HTML and CSS is rather simple, but I cant seem to center the div (livechat-wrapper) horizontally.

I just want the div to be as wide as the textarea, and placed just above the textarea, but it is "stuck" to the left side of my view.

Any ideas on how to do this?

<body >
  <div >

  </div>
  <form>
    <textarea maxlength="400" rows="1"id="input_field"  type="text" name="q" placeholder="Write a message..."></textarea>
  </form>

</body>
* {

    box-sizing: border-box;
    font-family: "Nunito", sans-serif;
  }
  
  html, body {
    background: linear-gradient(to bottom right, #FDFCFB, #E2D1C3);
    /*linear-gradient(to bottom right, #FDABDD, #374A5A);*/

    width: 800px;
    height: 600px
  }

form {
    display: flex;
    flex-direction: row;
    justify-content: center;
    position: absolute;
    bottom: 0;
    left: 0; 
    right: 0;
    padding-bottom: 10px;

}
.input_field {
    background: rgba(255, 255, 255, 0.4);
    border-radius: 10px;
    width: 90%;
    border: none;
    padding: 1.2em;
    outline: none;
    font-weight: 400;
    box-shadow: 1px 1px 1px black, -0.5px -0.5px white;
    border: none;
    resize: none; 
    outline: none;
  }

.livechat-wrapper {
    background: rgba(255, 255, 255, 0.4);
    box-shadow: 1px 1px 1px black, -0.5px -0.5px white;
    height: 80%;
    width: 90%;
    border-radius: 10px;
    border: 0.05em solid red;
    display: flex;
    flex-direction: row;
    justify-content: center;

 
}

I tried using on the div, but with no luck

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

CodePudding user response:

There are several ways to center a div horizontally using CSS. Here are a few examples:

Using margin: auto:

div {
  width: 50%; /* or any other width */
  margin: 0 auto;
}

This method works by setting the left and right margins to auto, which will push the div to the center of the parent element.

Using Flexbox:

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

This method works by using the justify-content property to center the div within the parent element

Using Grid:

div {
  display: grid;
  place-items: center;
}

This method works by using the place-items property to center the div within the parent element.

Using transform: translate:

div {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
  • Related