BonJon
BonJon

Reputation: 799

How to center absolute position element in my case

I am trying to create an element in the center of the parent element My question is how to make it always center responsively.

I have something like

html

<div class="test">
    <span class="d1">Test 1</span>
    <span class="d2">Test 2</span>
</div>

css

.test {
    position:relative;
}

.d1 {
    width:300px;
    height:200px;
    background-color: #789845;
}

.d2 {
    position: absolute;
    top:40%;
    left: ( not sure what to put here), I want this element always in the center no matter the width of browser is.
    width: 100px;
    background-color:#EEEE78;
}

I am not sure how to set the left value because if I set a static value, it will always be a bit off on varies browser width. Can someone help me about it? Thanks a lot!

Upvotes: 0

Views: 41

Answers (3)

Yandy_Viera
Yandy_Viera

Reputation: 4380

1- You can use left: 50% and transform (for unknown width) to achieve what you want like this:

.test {
    position:relative;
}

.d1 {
    width:300px;
    height:200px;
    background-color: #789845;
}

.d2 {
    position: absolute;
    top:40%;
    width: 100px;
    background-color:#EEEE78;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}
<div class="test">
    <span class="d1">Test 1</span>
    <span class="d2">Test 2</span>
</div>

2- or you can use left: 50% and margin-left: -(half width) (for known width)

.test {
    position:relative;
}

.d1 {
    width:300px;
    height:200px;
    background-color: #789845;
}

.d2 {
    position: absolute;
    top:40%;
    background-color:#EEEE78;  
    width: 100px;
    left: 50%;
    margin-left: -50px; /* - the half of width (100 / 2) */
}
<div class="test">
    <span class="d1">Test 1</span>
    <span class="d2">Test 2</span>
</div>

Upvotes: 2

AleshaOleg
AleshaOleg

Reputation: 2201

For any absoulte position element - exists just one overall rule margin-left: auto; margin-right: auto; left: 0; right: 0;.

Also, you should add width to your parent element, then children will know where is center. In your case it's .test class with width: 100%; (you can change it, as you want).

.test {
    position:relative;
    width: 100%;
}

.d1 {
    width:300px;
    height:200px;
    background-color: #789845;
}

.d2 {
    position: absolute;
    width: 100px;
    background-color:#EEEE78;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
}
<div class="test">
    <span class="d1">Test 1</span>
    <span class="d2">Test 2</span>
</div>

Upvotes: 2

Matt Komarnicki
Matt Komarnicki

Reputation: 5422

Try left 0 and right 0 as well as margin-left auto and margin-right auto. To avoid guessing always provide your fiddle.

Upvotes: 0

Related Questions