Есть ли какой-нибудь способ использовать flex вместо float, чтобы держать коробки справа и слева между содержимым?

#javascript #html #css

#язык JavaScript #HTML #CSS

Вопрос:

Я хочу создать пользовательский интерфейс, похожий на этот пример изображения, используя гибкий интерфейс и без отрицательного поля —

введите описание изображения здесь

Проблема в том, что я использовал плавающую и отрицательную маржу для создания одного и того же макета. Но я не хочу использовать отрицательное значение для установки зеленого div вне содержимого. Кроме того, я использовал поплавок, чтобы хранить содержимое вокруг зеленых ящиков. Но я хочу использовать flex вместо float.

Итак, подводя итог моему вопросу- Создайте эталонный макет, который не будет использовать какое-либо плавающее или отрицательное значение для выравнивания полей зеленым цветом.

Я добавил снимок кода здесь, чтобы взглянуть на мой HTML и CSS.

Любая помощь будет признательна. заранее спасибо.

 .container {  width: 50%;  text-align: justify;  margin: auto; }  .box {  background-color: green;  width: 20%;  padding: 15px;  margin: 15px; }  .right {  float: right;  margin-right: 0 !important;  margin-right: -15% !important; }  .left {  float: left;  margin-left: 0 !important;  margin-left: -15% !important; } 
 lt;div class="container"gt;  lt;div class="paragrah"gt;  electronictypesetting,remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheetscontainingLorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker includingversionsof Lorem  Ipsum. It is a long established fact that a reader will be distracted by the readable content of apage   lt;div class="box right"gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque porttitor aliquet leo, et suscipit nulla sodales at. Praesent dictum imperdiet lacus nec pharetra.  lt;/divgt;   when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distributionofletters, as opposed to using 'Content here, content here', making it look like readable English. Manydesktoppublishing packages and web page  editors now use Lorem Ipsum as their default model text, and a search for'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over theyears,sometimes by accident, sometimes on purpose (injected humour and  the like).Contrary to popular belief, Lorem Ipsum is not simply random text. Ithasroots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. RichardMcClintock, aLatin professor at Hampden-Sydney College in Virginia,  looked up one of the more obscure Latin words,consectetur,from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered theundoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus  Bonorum et Malorum"(TheExtremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics,verypopular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from alineinsection  1.10.32. There are many variations of passages of Lorem Ipsum available, but the majority havesufferedalteration in some form, by injected humour, or randomised words which don't look even slightly believable.Ifyou   lt;div class="box left"gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque porttitor aliquet leo, et suscipit nulla sodales at. Praesent dictum imperdiet lacus nec pharetra. Ut ut risus ipsum ac leo auctor convallis.  lt;/divgt;   are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden inthemiddle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks asnecessary,makingthis the first true generator  on the Internet. It uses a dictionary of over 200 Latin words, combined with ahandfulof model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum isthereforealways free from repetition, injected humour, or  non-characteristic words etc.he standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.Sections1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exactoriginalform,accompanied  by English versions from the 1914 translation by H. Rackham. But I must explain to you how allthismistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account ofthesystem, and expound the actual teachings  of the great explorer of the truth, the master-builder of humanhappiness.No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do notknowhowto pursue pleasure rationally encounter consequences that are  extremely painful. Nor again is there anyonewholovesor pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstancesoccurinwhich toil and pain can procure him some great pleasure. To take a trivial example,  which of us everundertakeslaborious physical exercise, except to obtain some advantage from it? But who has any right to find faultwith amanwho chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure?who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure? who chooses to enjoy a pleasure that has no.  lt;/divgt; lt;/divgt; 

Комментарии:

1. Это один из лучших вариантов использования float , flex но это не правильный выбор для этого.

2. Я согласен, что это практически единственный случай, для которого я бы использовал float . Отличный вопрос, кстати

3. flexbox не является и никогда не будет волшебным инструментом для всего

Ответ №1:

Нет.

Flexbox предназначен для размещения ящиков в ряд или столбец.

Float предназначен для обертывания текста вокруг полей.

Для этого вам нужен поплавок.

Ответ №2:

У вас есть два требования. Первое можно выполнить, второе-нет

Во-первых, текстовые поля с зелеными вставками должны находиться в содержимом паараграфа. Этого можно достичь, выделив абзац левым и правым отступом, рассчитав это исходя из требуемого поля, отступа и ширины элементов зеленой вставки, чтобы обеспечить достаточное пространство.

Во — вторых, поплавок не используется. flex здесь не может помочь, он одномерен, он не понимает концепцию текста, плавающего вокруг элемента. Это требование-то, для чего предназначен поплавок. Вам нужно продолжать использовать его здесь.

 .container {  width: min(80vw, 700px);  text-align: justify;  margin: auto; }  .paragraph {  background-color: pink;  padding: 0 calc(10%   15px); }  .box {  background-color: green;  width: 20%;  padding: 15px;  margin: 15px; }  .right {  float: right;  margin-right: 0 !important;  margin-right: -15% !important; }  .left {  float: left;  margin-left: 0 !important;  margin-left: -15% !important; } 
 lt;div class="container"gt;  lt;div class="paragraph"gt;  electronictypesetting,remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheetscontainingLorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker includingversionsof Lorem  Ipsum. It is a long established fact that a reader will be distracted by the readable content of apage   lt;div class="box right"gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque porttitor aliquet leo, et suscipit nulla sodales at. Praesent dictum imperdiet lacus nec pharetra.  lt;/divgt;   when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distributionofletters, as opposed to using 'Content here, content here', making it look like readable English. Manydesktoppublishing packages and web page  editors now use Lorem Ipsum as their default model text, and a search for'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over theyears,sometimes by accident, sometimes on purpose (injected humour and  the like).Contrary to popular belief, Lorem Ipsum is not simply random text. Ithasroots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. RichardMcClintock, aLatin professor at Hampden-Sydney College in Virginia,  looked up one of the more obscure Latin words,consectetur,from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered theundoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus  Bonorum et Malorum"(TheExtremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics,verypopular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from alineinsection  1.10.32. There are many variations of passages of Lorem Ipsum available, but the majority havesufferedalteration in some form, by injected humour, or randomised words which don't look even slightly believable.Ifyou   lt;div class="box left"gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque porttitor aliquet leo, et suscipit nulla sodales at. Praesent dictum imperdiet lacus nec pharetra. Ut ut risus ipsum ac leo auctor convallis.  lt;/divgt;   are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden inthemiddle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks asnecessary,makingthis the first true generator  on the Internet. It uses a dictionary of over 200 Latin words, combined with ahandfulof model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum isthereforealways free from repetition, injected humour, or  non-characteristic words etc.he standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested.Sections1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exactoriginalform,accompanied  by English versions from the 1914 translation by H. Rackham. But I must explain to you how allthismistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account ofthesystem, and expound the actual teachings  of the great explorer of the truth, the master-builder of humanhappiness.No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do notknowhowto pursue pleasure rationally encounter consequences that are  extremely painful. Nor again is there anyonewholovesor pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstancesoccurinwhich toil and pain can procure him some great pleasure. To take a trivial example,  which of us everundertakeslaborious physical exercise, except to obtain some advantage from it? But who has any right to find faultwith amanwho chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure?who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant  pleasure? who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids apain that produces noresultant pleasure? who chooses to enjoy a pleasure that has no.  lt;/divgt; lt;/divgt; 

Обратите внимание, что в этом фрагменте текста было исправлено написание абзаца. Кроме того, общая ширина была установлена как минимум, чтобы система фрагментов Stackoverflow, которая является узкой, пока вы не перейдете на полную страницу, могла вместить все. Розовый цвет был добавлен только для того, чтобы продемонстрировать, где сейчас находятся границы контента.