Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center a child element in CSS, even if it is larger than the parent?

Tags:

html

css

I would like to create a css class so a div can be placed in the center of its parent. The code I am using is:

.centered {     position: absolute;     margin: auto;      bottom: 0px;     left: 0px;     top: 0px;     right: 0px; } 

It works if the parent is larger than the child element, or has the same size: https://jsfiddle.net/cy8dn1km/

But if the child is larger, then its center is not positioned at the center of its parent. Instead their left borders will be at the same place, and the child element will be extended only to right:

https://jsfiddle.net/797L7nce/

Something is wrong with the horizontal centering.

How is it possible to fix it using CSS only (without using CSS 2D/3D transformations), without adding new container elements?

like image 334
Iter Ator Avatar asked Jul 12 '16 11:07

Iter Ator


People also ask

How do I center my child in CSS?

Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.

How do you position an element to the center in CSS?

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

How do I center my child div?

Simply give the child element a property of margin: with a value of 0 auto; . This will automatically size the margin on the left and right sides of the div evenly to one another.

How do you make a child div element wider than the parent div?

In this case, we set the child element's width to be 100% of the viewport width by using a percentage viewport unit (vw), then, we move it to the left side (by the distance of the viewport's half, minus 50% of the width of the parent element) with the left property.


1 Answers

Add left: 50%; transform: translate(-50%, 0);and remove right: 0px;

.centered {     position: absolute;     margin: auto;     display: block;     bottom: 0px;     top: 0px;     left: 50%;     transform: translate(-50%, 0); } 

Demo

like image 105
Ismail Farooq Avatar answered Sep 30 '22 05:09

Ismail Farooq