gkeenley
gkeenley

Reputation: 7378

React Native: 'top' property behaving as expected, but 'bottom' isn't

I have the following code in my React Native app:

<View
  style={{
    width: 50,
    height: 50,
    borderWidth: 1,
  }}
>
  <View style={{
    width: 5,
    height: 5,
    backgroundColor: 'red',
    top: 10,
    left: 10
  }}></View>
</View>

As expected, this results in:

enter image description here

However, if I swap top for bottom, I get this:

enter image description here

If I change the child element to position: absolute, it works as expected:

enter image description here

What I Want To Know:

1) Why does the red dot go above the black square in the second image?

2) Since the red dot is the only child of the black square, why does adding position: absolute change anything?

3) Why does top behave as expected in all three images, but bottom behaves as expected only in the third?

Upvotes: 1

Views: 1307

Answers (2)

Travis James
Travis James

Reputation: 1939

1) Because without specifying position: absolute all position commands are relative to where the element is initially.

2) It changes how the positions commands (top, left, right, bottom ) are interpreted relative to the parent element

3) Because top refers to the same place regardless of what position is set to, but buttom could refer to a different place depending on if you have position set to relative or absolute

Upvotes: 2

Mateusz Falkowski
Mateusz Falkowski

Reputation: 436

In React-Native, every layout element is relatively positioned by default, so 10px relatively from the bottom of initial position lays out of the container, it is proper behavior.

Set the child's position to absolute, if You want to position the dot against the bounds of the container.

    <View
      style={{
        width: 50,
        height: 50,
        borderWidth: 1,
        position: 'relative' // by default anyway
      }}
    >
      <View
        style={{
          width: 5,
          height: 5,
          backgroundColor: "red",
          bottom: 10,
          left: 10,
          position: 'absolute'
        }}
      />
    </View>

Upvotes: 2

Related Questions