英文:
How to use flexbox in Angular
问题
我正在学习Angular,当我尝试在body上使用flexbox时似乎不起作用,但在其他元素上使用它有效。例如,我尝试创建一个简单的计数器应用,并希望将所有内容居中,但似乎不起作用。
我搜索了一下,发现大部分人都在使用Angular Flex-Layout,那是我需要使用的吗,还是我遗漏了什么?
app.component.html
<div class="content">
<h2 class="counter">{{num}}</h2>
<button class="btn" (click)="increment($event)">+</button>
<button class="btn" (click)="decrement($event)">-</button>
</div>
app.component.css
body {
display: flex;
align-content: center;
}
.content {
display: flex;
}
英文:
I'm learning Angular and when I try to use flexbox on the body it doesn't seem to work, but using it on other elements works. For example what I'm trying to do is I made a simple counter app and I want to center everything but it doesn't seem to work.
I googled and all I could see was people using Angular Flex-Layout so is that what I need to use or am I missing something?
app.component.html
<div class="content">
<h2 class="counter">{{num}}</h2>
<button class="btn" (click)="increment($event)">+</button>
<button class="btn" (click)="decrement($event)">-</button>
</div>
app.component.css
body {
display: flex;
align-content: center;
}
.content {
display: flex;
}
答案1
得分: 1
你构建后的HTML如下:
<body>
<app-root>
<!-- 你的组件的HTML代码 -->
</app-root>
</body>
所以你在这里漏掉了一个步骤。
在你的app.component.scss
文件中:
:host {
height: 100%;
display: flex;
align-content: center;
}
.content {
display: flex;
}
英文:
Your HTML after build is
<body>
<app-root>
<!-- HTML Code of your component -->
</app-root>
</body>
So you're missing a step here.
In your app.component.scss
file :
:host {
height: 100%;
display: flex;
align-content: center;
}
.content {
display: flex;
}
答案2
得分: 0
组件的CSS文件是有作用范围的。 这意味着它们只适用于组件中的元素(在您的情况下是app.component.html)
如果您想在组件外部编写样式,可以使用全局样式表,例如 src/styles.css
,在 angular.json
中定义。它们的工作方式与常规CSS相同。
英文:
The component CSS files are scoped. That means they only applies to elements in the component (app.component.html in your case)
https://angular.io/guide/component-styles
If you want to write styles outside components, you can use global stylesheets, e.g. src/styles.css
, defined in angular.json
. They work just like regular css
答案3
得分: -1
尝试添加 justify-content
和 align-items
来将内容居中对齐。您还需要设置 html
和 body
元素的 height
和 min-height
。
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
文档链接在这里。
align-items
属性将项目在交叉轴上对齐。
justify-content
将项目在主轴上对齐。
英文:
Try adding justify-content
and align-items
to align the content to center. You will also need to set height
and min-height
of html
and body
elements.
html {
height: 100%;
}
body {
min-height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
Documentation is here.
align-items
property aligns the item on the cross axis.
justify-content
aligns the item on the main axis.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论