简体   繁体   English

将 div 与其他 div 对齐

[英]Aligning divs in relation to other divs

I'm trying to replicate something like this:我正在尝试复制这样的东西:文本 . .

The red div (the container) is centered horizontaly and hasn't a fixed width.红色 div(容器)水平居中,没有固定宽度。 The "title" div inside it should set the width of the container by being the widest div inside it, and the "welcome to" and "subtitle" divs are attached to the "title" div and the left/right of the container.其中的“title” div 应该设置容器的宽度,设置为容器内最宽的 div,“welcome to”和“subtitle” div 附加到“title” div 和容器的左/右。

I'm struggling to understand how I can put my "welcome to" div to the left, before having set the "title" div which gives the width of the container.在设置给出容器宽度的“标题”div 之前,我很难理解如何将“欢迎来到”div 放在左侧。

For the moment, I have this code:目前,我有这个代码:

.container {
text-align: center;
}

.welcome_to{
text-align: left;
}

.subtitle{
text-align:right;
}

.title{
}

It centers the title div, but put the other divs at the edges of the screen, and not of the container.它将标题 div 居中,但将其他 div 放在屏幕边缘,而不是容器边缘。

This should give you a start这应该给你一个开始

 .container { border: 3px solid red; display: flex; flex-direction: column; font-size: 2em; }.left, .center, .right { border: 3px solid blue; }.full-width { width: 100%; }.left { display: flex; align-self: flex-start; }.center { display: flex; align-self: center; justify-content: center; }.right { display: flex; align-self: flex-end; }
 <div class="container"> <div class="left">Left</div> <div class="center full-width">Center and full width</div> <div class="right">right</div> </div>

text-align aligns text, not block elements. text-align对齐文本,而不是块元素。 The best way here is to use flexbox:这里最好的方法是使用 flexbox:

 /* This is the actual code */.container { display: flex; flex-direction: column; }.welcome-to { align-self: flex-start; width: 50%; }.title { text-align: center; }.subtitle { align-self: flex-end; width: 50%; text-align: right; } /* Decoration only */.container { border: 3px solid red; }.container > * { box-sizing: border-box; padding: 1rem; border: 3px solid blue; }
 <div class="container"> <div class="welcome-to">Welcome to</div> <div class="title">Title</div> <div class="subtitle">Subtitle</div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM