Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: center element within a <div> element

Tags:

css

To center an HTML element I can use the CSS left: 50%;. However, this centers the element with respect to the whole window.

I have an element which is a child of a <div> element and I want to center the child with respect to this parent <div>, not the whole window.

I do not want the container <div> to have all its content centered, just the one specific child.

like image 250
Randomblue Avatar asked Jul 24 '11 21:07

Randomblue


People also ask

How do I center a centered element in CSS?

To just center the text inside an element, use text-align: center; This text is centered.

How do I center a div vertically within a div?

Vertically centering div items inside another div Just set the container to display:table and then the inner items to display:table-cell . Set a height on the container, and then set vertical-align:middle on the inner items.

How do I center an image in a div using CSS?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.


1 Answers

Set text-align:center; to the parent div, and margin:auto; to the child div.

#parent {      text-align:center;      background-color:blue;      height:400px;      width:600px;  }  .block {      height:100px;      width:200px;      text-align:left;  }  .center {      margin:auto;      background-color:green;  }  .left {      margin:auto auto auto 0;      background-color:red;  }  .right {      margin:auto 0 auto auto;      background-color:yellow;  }
<div id="parent">      <div id="child1" class="block center">          a block to align center and with text aligned left      </div>      <div id="child2" class="block left">          a block to align left and with text aligned left      </div>      <div id="child3" class="block right">          a block to align right and with text aligned left      </div>  </div>

This a good resource to center mostly anything.
http://howtocenterincss.com/

like image 171
pasine Avatar answered Sep 28 '22 10:09

pasine