我希望我的 text
和 button
位于屏幕顶部,但是这两个元素之间有一些间隙,所以我添加了 marginBottom
到我的 text
然后那个 text
到了顶部。但我希望 button
位于顶部,所以我也将 marginBottom
添加到 button
,但现在它不会位于顶部。
如何将其置于顶部?风格问题从何而来?也请解释我的错误。
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={{ margin: 16, marginBottom: '80%', backgroundColor: 'black' }}>Hello World</Text>
<View style={{ marginBottom: '80%' }}>
<Button title='Click me' />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
最佳答案
您正在使用 alignItems: 'center'
和 justifyContent: 'center'
.
这两个属性结合在一起构成了 container
的内容。位于中心。 alignItems:center
内容垂直居中,justifyContent:center
内容水平居中。
自 Text
是上面的子元素,给它一个 marginBottom
将它与 View
隔开包含 Button
的元素.如果你比较你的屏幕有没有那个marginBottom
在 Text
上您会注意到,如果包含 marginBottom
,该按钮也会稍微移动到底部。在 Text
上.
简而言之,您的代码完全按照您的要求执行:container
尝试将所有 child 定位到它的中心。
要解决此问题,您可能需要删除 container:{ alignItems:'center', }
属性(property)。这很可能会将您的所有元素推到容器的顶部。之后你可以简单地使用 marginTop
在你的 Text
元素将内容向下推。
关于css - 我怎样才能将我的按钮向上移动,因为文本是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74639097/